Skip to main content

FastWorker

Struct FastWorker 

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

The worker side of the fast lane. It reads a fast task stream with a consumer group and answers each task on the task’s own reply key, while its caller waits:

  • It creates the group when missing, and again when it goes.
  • A task whose reply_to fails is_valid_rpc_reply_to for its task_id and the worker’s FastWorkerConfig::kind is acknowledged and deleted unanswered.
  • Then a task whose deadline_ms, a plain decimal integer of Unix milliseconds, is before the worker’s clock when it’s read is acknowledged and deleted unanswered: its caller has given up. A clock that reads exactly the deadline still answers. A missing, empty or unreadable deadline (a sign, a point, an exponent, a blank) is no deadline. The deadline isn’t checked again after the work, so a task that ran past it is still answered.
  • Every other entry gets exactly one result, as a Worker would write it: the handler’s reply, its error, an internal error for a panic, or an error for an entry that isn’t a valid task. The result is added to the reply key, the key’s expiry set to FastWorkerConfig::reply_ttl, and the task acknowledged and deleted, in that order. A write that fails is logged, not retried: the caller won’t wait for a retry.
  • A task the worker can’t serve gets an error result, not silence: a handler that abandons it (Failure::abandon, or Context::checkpoint once stopping), and a task no thread could be started for, are answered with an internal error, so the caller falls back at once.
  • Nothing is reclaimed, leased or retried. An entry a dead worker left pending is never run again; an operator deletes old fast entries, and their callers have timed out.
  • On Stopper::stop it reads no more and answers every task it has read, however long that takes: a caller may still be waiting. A handler that should stop sooner checks Context::checkpoint, and its task is answered with an internal error. Then the worker removes its consumer when it owns nothing.

A fast worker runs on threads of its own, so it can run in the same process as a bulk Worker, on the same Streams, without waiting for it: a bulk task holds a bulk slot, never a fast one. Share one handler between them by cloning an Arc into each closure.

use std::time::Duration;
use legit_streams::{Clock, Failure, FastCaller, FastWorker, FastWorkerConfig, MemoryStreams, Reply, Task};

let clock = Clock::manual(1_700_000_000_000);
let streams = MemoryStreams::with_clock(clock.clone());
let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
let running = FastWorker::new(config, streams.clone(), |task: &Task, _: &_| {
    let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
    Ok(Reply::new().field("result", text.len().to_string()))
})?
.clock(clock.clone())
.spawn()?;

let caller = FastCaller::new(streams.clone(), "hash_tasks:fast", "hash").clock(clock.clone());
let task = Task::builder("app", "query", "0").field("text_data", "hello").build()?;
let result = caller.call(&task, Duration::from_secs(3))?;
assert_eq!(result.get("result"), Some("5"));

running.stop();
clock.advance(Duration::from_secs(1));
assert_eq!(running.join()?.results, 1);

Implementations§

Source§

impl FastWorker

Source

pub fn new( config: FastWorkerConfig, streams: impl Streams + 'static, handler: impl Handler, ) -> Result<Self>

A fast worker with these settings, on the system clock.

§Errors

Error::InvalidConfig for settings that can’t work, such as an empty stream name, a task stream beginning with results: or dead:, a concurrency of 0, or a reply expiry under a second.

use std::time::Duration;
use legit_streams::{Error, FastWorker, FastWorkerConfig, MemoryStreams, Reply};

let config = FastWorkerConfig { reply_ttl: Duration::ZERO, ..FastWorkerConfig::new("s", "g", "c", "hash") };
let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()));
assert!(matches!(worker, Err(Error::InvalidConfig(_))));
Source

pub fn clock(self, clock: Clock) -> Self

Run on clock rather than the system clock, such as a manual clock in tests: deadlines are checked against its time. Take FastWorker::stopper after this.

use legit_streams::{Clock, FastWorker, FastWorkerConfig, MemoryStreams, Reply};

let config = FastWorkerConfig::new("s", "g", "c", "hash");
let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?.clock(Clock::manual(0));
Source

pub fn stopper(&self) -> Stopper

The handle that stops this worker.

use legit_streams::{FastWorker, FastWorkerConfig, MemoryStreams, Reply};

let config = FastWorkerConfig::new("s", "g", "c", "hash");
let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
assert!(!worker.stopper().is_stopped());
Source

pub fn config(&self) -> &FastWorkerConfig

The worker’s settings.

use legit_streams::{FastWorker, FastWorkerConfig, MemoryStreams, Reply};

let config = FastWorkerConfig::new("s", "g", "c", "hash");
let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
assert_eq!(worker.config().consumer, "c");
Source

pub fn spawn(self) -> Result<Running>

Run the worker on a thread of its own.

§Errors

Error::Thread when the thread can’t be started.

use legit_streams::{FastWorker, FastWorkerConfig, RedisStreams, Reply};

let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
let running = FastWorker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?.spawn()?;
running.stop();
running.join()?;
Source

pub fn run(&self) -> Result<Report>

Run the worker on this thread until Stopper::stop.

§Errors

Error::Redis when the group can’t be created at the start. Once running, a failed command is logged and the loop goes on, never returned.

use legit_streams::{FastWorker, FastWorkerConfig, RedisStreams, Reply};

let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
let report = FastWorker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?.run()?;
println!("{} answered, {} expired", report.results, report.expired);

Trait Implementations§

Source§

impl Debug for FastWorker

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for FastWorker

§

impl !UnwindSafe for FastWorker

§

impl Forget for FastWorker

§

impl Freeze for FastWorker
where *const ArcInner<FastWorkerConfig> is !null: Freeze, PhantomData<ArcInner<FastWorkerConfig>>: Freeze, *const ArcInner<dyn Streams> is !null: Freeze, PhantomData<ArcInner<dyn Streams>>: Freeze, *const ArcInner<dyn Handler> is !null: Freeze, PhantomData<ArcInner<dyn Handler>>: Freeze, *const ArcInner<Inner> is !null: Freeze, PhantomData<ArcInner<Inner>>: Freeze, *const ArcInner<Control> is !null: Freeze, PhantomData<ArcInner<Control>>: Freeze,

§

impl Move for FastWorker

§

impl Send for FastWorker
where Arc<FastWorkerConfig>: Send, Arc<dyn Streams>: Send, Arc<dyn Handler>: Send, Arc<Inner>: Send, Arc<Control>: Send,

§

impl Sync for FastWorker
where Arc<FastWorkerConfig>: Sync, Arc<dyn Streams>: Sync, Arc<dyn Handler>: Sync, Arc<Inner>: Sync, Arc<Control>: Sync,

§

impl Unpin for FastWorker
where Arc<FastWorkerConfig>: Unpin, Arc<dyn Streams>: Unpin, Arc<dyn Handler>: Unpin, Arc<Inner>: Unpin, Arc<Control>: Unpin,

§

impl UnsafeUnpin for FastWorker
where *const ArcInner<FastWorkerConfig> is !null: UnsafeUnpin, PhantomData<ArcInner<FastWorkerConfig>>: UnsafeUnpin, *const ArcInner<dyn Streams> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Streams>>: UnsafeUnpin, *const ArcInner<dyn Handler> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Handler>>: UnsafeUnpin, *const ArcInner<Inner> is !null: UnsafeUnpin, PhantomData<ArcInner<Inner>>: UnsafeUnpin, *const ArcInner<Control> is !null: UnsafeUnpin, PhantomData<ArcInner<Control>>: 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<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> 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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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