Skip to main content

Workers

Struct Workers 

Source
pub struct Workers { /* private fields */ }
Expand description

Concurrency policy for one subscriber’s dispatch loop, declared with the workers(..) or threads(..) macro argument (or Workers::sequential by default).

  • workers(n): n long-lived workers, tasks of the runtime the app runs on, process up to n deliveries of the subscriber concurrently; a free worker takes the next one. Back-pressure holds: the stream is not polled while n deliveries are in flight. Global processing order is lost by design.
  • workers(n, by_key): the same n workers as sequential lanes; a delivery goes to the lane picked by hashing its partition_key, so per-key ordering is preserved. Messages without a key rotate over the lanes.
  • threads(n): n dedicated threads of the subscription’s own, each with a current-thread runtime, for a handler that computes. The subscription’s loop stays on the app’s runtime and spreads deliveries over the threads round-robin; decoding, the handler and settling run on the thread a delivery was handed to, and only there. The app’s runtime stays free for I/O, timers and the other subscriptions.
  • threads(n, by_key): the same threads as sequential lanes by partition key.

The workers or threads and the queues that feed them are made when the subscription starts: handing a delivery to one allocates nothing.

The default is sequential dispatch (workers(1)).

Implementations§

Source§

impl Workers

Source

pub const fn sequential() -> Workers

Sequential dispatch: one delivery at a time, in stream order. The default.

Source

pub const fn pool(count: NonZero<usize>) -> Workers

A pool of up to count concurrent deliveries. One behaves like sequential dispatch.

Source

pub const fn keyed(count: NonZero<usize>) -> Workers

count sequential lanes keyed by the message partition_key: per-key ordering is preserved. One lane behaves like sequential dispatch.

Source

pub const fn threads(count: NonZero<usize>) -> Workers

count dedicated threads for a CPU-bound handler: the subscription’s deliveries are handled on threads of its own, each running a current-thread runtime, so the handler’s computation holds up none of the app runtime’s threads. The router-chain spelling of threads(n).

§Examples
use ruststream::memory::prelude::*;
use serde::Deserialize;

#[derive(Deserialize)]
struct Image {
    id: u64,
}

#[subscriber("images.resize")]
async fn resize(image: &Image) -> HandlerOutcome {
    tracing::info!(image.id, "resized");
    HandlerOutcome::ack()
}

fn images() -> Router<MemoryBroker, impl RouterDef<MemoryBroker>> {
    // Resizing computes, so it runs on eight threads of its own.
    Router::new()
        .include(resize)
        .workers(Workers::threads(nonzero!(8)))
}

fn app() -> RustStream {
    RustStream::new(AppInfo::new("images", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
        b.include_router(images());
    })
}
Source

pub const fn threads_keyed(count: NonZero<usize>) -> Workers

count dedicated threads as sequential lanes keyed by the message partition_key: a key always lands on the same thread, so per-key ordering is preserved. The router-chain spelling of threads(n, by_key).

§Examples
use ruststream::memory::prelude::*;
use serde::Deserialize;

#[derive(Deserialize)]
struct Image {
    id: u64,
}

#[subscriber("images.resize")]
async fn resize(image: &Image) -> HandlerOutcome {
    tracing::info!(image.id, "resized");
    HandlerOutcome::ack()
}

fn images() -> Router<MemoryBroker, impl RouterDef<MemoryBroker>> {
    // One tenant's images stay in order: a key always lands on the same thread.
    Router::new()
        .include(resize)
        .workers(Workers::threads_keyed(nonzero!(4)))
}

fn app() -> RustStream {
    RustStream::new(AppInfo::new("images", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
        b.include_router(images());
    })
}
Source

pub const fn count(&self) -> NonZero<usize>

How many deliveries (or batches) are handled at once: the workers, the keyed lanes or the dedicated threads. One for sequential dispatch.

§Examples
use ruststream::memory::prelude::*;
use ruststream::runtime::{Declared, SubscriberBuilder};

/// A broker crate's mount step: one prefetch window per delivery in flight.
pub trait Prefetch: Declared {
    fn prefetch(self, per_delivery: usize) -> Self::Settings
    where
        Self::Settings: PrefetchStep,
    {
        self.declare().apply_prefetch(per_delivery)
    }
}

impl<Def: Declared> Prefetch for Def {}

pub trait PrefetchStep: Sized {
    fn apply_prefetch(self, per_delivery: usize) -> Self;
}

impl<Def, State, DefCodec> PrefetchStep
    for SubscriberBuilder<Def, MemorySource, State, DefCodec>
{
    fn apply_prefetch(self, per_delivery: usize) -> Self {
        let window = self.dispatch().count().get() * per_delivery;
        tracing::info!(window, "prefetch window");
        self
    }
}

#[subscriber(MemorySource)]
async fn audit(order: &u64) -> HandlerOutcome {
    tracing::info!(order, "audited");
    HandlerOutcome::ack()
}

fn app() -> RustStream {
    RustStream::new(AppInfo::new("audit", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
        // The step sees the eight workers named before it: a window of 80.
        b.include(audit.name("orders").workers(nonzero!(8)).prefetch(10));
    })
}
Source

pub const fn by_key(&self) -> bool

Whether deliveries go to sequential lanes by their partition_key rather than to whichever worker is free.

§Examples
use ruststream::memory::prelude::*;
use ruststream::runtime::{Declared, SubscriberBuilder};

/// A broker crate's mount step: keyed lanes keep a key's order, so the broker can ask the
/// server for unordered delivery only when nothing reads the key.
pub trait Ordering: Declared {
    fn log_ordering(self) -> Self::Settings
    where
        Self::Settings: OrderingStep,
    {
        self.declare().apply_log_ordering()
    }
}

impl<Def: Declared> Ordering for Def {}

pub trait OrderingStep: Sized {
    fn apply_log_ordering(self) -> Self;
}

impl<Def, State, DefCodec> OrderingStep
    for SubscriberBuilder<Def, MemorySource, State, DefCodec>
{
    fn apply_log_ordering(self) -> Self {
        let ordered = self.dispatch().by_key();
        tracing::info!(ordered, "per-key ordering");
        self
    }
}

#[subscriber(MemorySource::new("orders"), workers(4, by_key))]
async fn audit(order: &u64) -> HandlerOutcome {
    tracing::info!(order, "audited");
    HandlerOutcome::ack()
}

fn app() -> RustStream {
    RustStream::new(AppInfo::new("audit", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
        b.include(audit.log_ordering());
    })
}
Source

pub const fn placement(&self) -> Placement

Where the deliveries run: as tasks of the app’s runtime, or on dedicated threads of the subscription’s own.

§Examples
use ruststream::memory::prelude::*;
use ruststream::runtime::{Declared, Placement, SubscriberBuilder};

/// A broker crate's mount step: a dedicated thread keeps a connection of its own.
pub trait Sessions: Declared {
    fn sessions(self) -> Self::Settings
    where
        Self::Settings: SessionStep,
    {
        self.declare().apply_sessions()
    }
}

impl<Def: Declared> Sessions for Def {}

pub trait SessionStep: Sized {
    fn apply_sessions(self) -> Self;
}

impl<Def, State, DefCodec> SessionStep
    for SubscriberBuilder<Def, MemorySource, State, DefCodec>
{
    fn apply_sessions(self) -> Self {
        let per_thread = self.dispatch().placement() == Placement::Threads;
        tracing::info!(per_thread, "one session per thread");
        self
    }
}

#[subscriber(MemorySource::new("images"), threads(2))]
async fn resize(image: &u64) -> HandlerOutcome {
    tracing::info!(image, "resized");
    HandlerOutcome::ack()
}

fn app() -> RustStream {
    RustStream::new(AppInfo::new("images", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
        b.include(resize.sessions());
    })
}

Trait Implementations§

Source§

impl Clone for Workers

Source§

fn clone(&self) -> Workers

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Copy for Workers

Source§

impl Debug for Workers

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for Workers

Source§

fn default() -> Workers

Returns the “default value” for a type. Read more
Source§

impl Eq for Workers

Source§

impl PartialEq for Workers

Source§

fn eq(&self, other: &Workers) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Workers

Auto Trait Implementations§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PublishedThrough<DefaultSlot> for T

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = !

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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