legit-streams 0.1.3

A Redis Streams work contract for task and result envelopes, with a worker loop that leases, reclaims and replies, a producer and a result reader
Documentation

legit-streams

A work contract over Redis Streams in Rust: typed task and result envelopes, a worker loop that leases, reclaims and replies, a producer with a depth check, a result reader, and a fast lane for work a caller waits for. It's a plain Rust library with no framework dependency and no async runtime: blocking calls and threads.

It speaks an existing contract, version 1 of an envelope that a PHP producer and Python workers already exchange, so a Rust program can take part on either side without inventing a second format. This README is the public statement of that contract. An in-memory double of the stream commands, on a clock the test moves, makes all of it testable without a server.

Requirements

Rust 1.99 or newer, and Redis 6.2 or newer (XAUTOCLAIM arrived in 6.2). It has been run against Redis 8.0.5.

The Redis user a worker connects as needs, on its task stream, xreadgroup, xautoclaim, xpending, xclaim, xack, xdel and xgroup, plus eval (the lease renewal and release are server-side scripts that call xpending and xclaim), and xadd on the result streams. A fast worker also needs expire on the reply keys; a fast caller needs xadd on the fast task stream and xread, xdel and del. A producer needs xadd and xlen on its task stream; a result reader needs xreadgroup, xack, xdel, xgroup, xautoclaim and xpending on its result stream. xinfo on the task stream is needed only by a caller of Streams::group_backlog: no worker, producer or reader of this crate calls it by itself.

Installation

[dependencies]
legit-streams = "0.1"

A first run

One Redis, one worker and one producer, for a made-up kind of task, length, whose worker answers each task with the length of its text. In a first terminal, start a throwaway Redis:

docker run --rm -p 6379:6379 redis:8

In a second, from a checkout of this crate, start the worker. It creates its consumer group, serves length_tasks for a minute, then stops cleanly:

REDIS_URL=redis://127.0.0.1:6379 cargo run --example worker

In a third, within that minute, send three tasks and wait for their results:

REDIS_URL=redis://127.0.0.1:6379 cargo run --example producer

The producer prints each task it sends, then each result as the worker answers it. The order doesn't matter: tasks sent before the worker starts wait in the stream, and the producer waits up to 30 s for its results. REDIS_URL=redis://127.0.0.1:6379 cargo run --example fast runs the fast lane on the same server: a fast worker and a caller waiting for its reply, in one process.

Without REDIS_URL, each example runs on the in-memory double and needs no server.

The contract in a page

This is version 1 of the contract. A task carries its version in the v field. A producer sends v = 1; a worker takes a task without v as version 1, since older producers send none, and never runs a task whose v is present and isn't 1: it answers it with the error type unsupported_version. A task read without v keeps its fields as they were; Producer::send and FastCaller::call send it on with v = 1 after source, and refuse with Error::TooLarge, sending nothing, when the added field takes it over the bounds below.

Names. Each kind of work has a name, {kind}, of 1 to 16 characters matching ^[a-z0-9_-]{1,16}$, and its keys are named after it. With a kind hash:

What Name Example
Bulk task stream {kind}_tasks hash_tasks
Worker group {kind}_workers, one group per task stream hash_workers
Default result stream, for a task that names no reply stream {kind}_results hash_results
Fast task stream, read with the same group {kind}_tasks:fast hash_tasks:fast
An application's result stream results:{app}:{kind} results:app:hash
A fast task's reply key results:{app}:{kind}:rpc:{task_id} results:app:hash:rpc:app_01JDV3XK6T9Q4M8R2B7C5N1P0W
Tasks an operator has set aside dead:{stream} dead:hash_tasks

legit-hasher is a worker of this contract and serves the kind hash.

A kind never uses a task stream name that begins with results: or dead:: this crate's workers, fast workers, producers and fast callers refuse one with Error::InvalidConfig.

An operator that sets a task aside may answer it with a max_deliveries_exceeded error result, written after the task has left the live stream, so its producer isn't left waiting. A reader must not rely on it: a task set aside can also go unanswered, as a task can be answered twice.

Streams and groups. An application adds each task to a task stream with XADD. Workers read it through one consumer group, each under its own consumer name, so each task goes to one worker. Redis keeps every delivered, unacknowledged entry in the group's pending list, with the consumer that owns it, how long it has sat idle and how many times it has been delivered.

Leased workers only. The contract has two ways of recovering the tasks of a worker that dies, and this crate implements one: the leased model below, in which a worker renews a lease on each task it runs and claims tasks whose lease has lapsed. Leased and unleased workers must not share a group: a Worker of this crate would claim an unleased worker's running tasks once they sat idle past the claim threshold. Run this crate's workers only on groups whose every worker renews leases.

The task envelope. A task is a flat map of string fields. A producer never repeats a field name; a reader may refuse an entry that does, or take the last occurrence, never the first. This crate refuses it (Error::DuplicateField). An empty value means the field is absent, unless the field says otherwise. task_id, model_type, model_id, task_name and source are required and not empty, of a producer and of a task a worker reads; model_name is required and may be empty; v is required of a producer. This crate's builder always writes all of them.

Field Meaning
task_id 1 to 64 ASCII letters, digits, _ and -: unique across applications, and the key the result carries back. The crate generates {app}_{ULID}, the recommended form; a worker runs any id of that alphabet
model_type, model_id The application's record type and id, echoed back untouched; at most 256 bytes each from a producer
task_name A label for logs, default unless set; at most 256 bytes from a producer
model_name Which model to use; empty means the worker's default
source The producing application. A producer sends 1 to 32 lowercase ASCII letters, digits, _ and -, the form the crate builds; a worker reading a task requires only that it isn't empty
v The envelope version, 1
reply_to The stream the result goes to, results:{app}:{kind}, matching ^results:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$ and at most 128 bytes. Optional on an instance with a single application; with more than one, every producer must send it and every worker must honour it
anything else The payload, such as text_data, image_data (base64) or audio_url, and optional settings such as embed_role, prefix, dimensions, embedder_key and metadata. This crate keeps them in order and never interprets them; a worker echoes embedder_key and metadata on its result when the task has them

A producer names its fields in lowercase snake case, [a-z_][a-z0-9_]*, at most 64 bytes; the builder refuses any other name. A reader is looser: it takes any name of up to 256 bytes.

A task the worker can't read, because a field of the envelope is missing or empty, its task_id breaks the rule above, a name is repeated, a field name or value isn't UTF-8, or the entry is outside the size bounds (a field name over 256 bytes among them), is never run and never left pending:

  • When the entry has a non-empty task_id, the worker answers it with an error result of type invalid_task, carrying the task_id exactly as it was sent, even one outside the rule, routed as any result is, and removes the task. It builds no key from that id.
  • When it has none, the worker logs it and removes it. This crate counts a task_id over 256 bytes, or one that isn't UTF-8, as none.

The same answer, with its own error type, goes to a task refused for its version or its delivery count. These are the only reasons a worker answers a task without running it. The delivery count comes first, before the envelope is read, so an entry that breaks a worker while being read is stopped too: an unreadable entry past the delivery limit is answered max_deliveries_exceeded. A result reader takes such a result like any other: it requires only a non-empty task_id.

When a worker answers a task whose model_type, model_id or task_name is missing, empty or over 256 bytes, it writes the literal unknown in its place, whether it ran the task or not. That alone is no reason to refuse a task. A result's model_name is never replaced: where nothing ran, it is the name the task asked for, which may be empty. The code stays invalid_task even when the fields the result echoes are over the worker's limits: optional echoes such as metadata are dropped and the three above become unknown, while model_name is kept as the task asked; it is emptied only when it alone is too large to carry. A handler's error is kept the same way, its code and message, its fields and echoes dropped as they must be. A handler's successful result over the limits becomes a result_too_large error; when even that doesn't fit, it's cut to its identity and error, with each echo over 1,024 bytes written as unknown and a model_name over 1,024 bytes emptied.

Reserved field names. Names starting with _ are reserved for whoever operates the Redis instance, and requeue_count and requeued_at for workers that put a task back. A producer never sends a payload field with a reserved name (the builder refuses one with Error::ReservedField). A worker ignores fields it doesn't know, these included, and passes them through untouched if it publishes the entry again.

Leases. A worker that takes a task holds a lease on it while it runs: every 60 s, the reference value, it renews the lease. A renewal is one atomic step on the server: if, at the instant it runs, the entry is pending in the group for this consumer, its idle time becomes 0 and nothing else changes, neither the owner nor the delivery count; otherwise nothing changes, and the lease is lost. A check followed by a separate claim doesn't conform: another worker's claim could land between the two, and the second command would take the entry straight back. The crate sends this script, with KEYS[1] the task stream and ARGV the group, the consumer and the entry id:

-- 1  renewed: pending for this consumer, idle time now 0
-- 0  lost: not pending in the group (acknowledged or deleted)
-- -1 lost: pending for another consumer; nothing changed
local p = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[3], ARGV[3], 1)
if #p == 0 then return 0 end
if p[1][2] ~= ARGV[2] then return -1 end
local c = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[2], 0, ARGV[3], 'JUSTID')
if #c == 0 then return 0 end
return 1

The second 0 is an entry still pending but already deleted from the stream: XCLAIM drops it from the pending list and returns nothing. Lost is one outcome with two causes: the entry isn't pending in the group (acknowledged or deleted, or the group itself is gone, NOGROUP), or it's pending for another consumer. A server may report a NOGROUP raised inside the script with the code ERR and the original error in the message; the crate reads NOGROUP in either place. A worker treats both causes the same: it stops at its next safe point, writes no result, and neither acknowledges nor deletes the entry. A renewal that gets another error reply or times out says nothing about the lease: the worker keeps working and tries again at the next interval. A worker also renews right before each try of writing a result and of acknowledging the task, retries included, and stops, writing and acknowledging nothing more, as soon as it knows the lease is lost. Reading the consumer's own history with XREADGROUP … 0 isn't a renewal: it resets the idle time but counts a delivery on every read.

Claiming. A worker claims entries whose worker died or stalled before it reads new ones. It claims only entries idle for at least the claim threshold, 300 s by default here, the contract's reference value, with XAUTOCLAIM. A deployment may choose other values, but the threshold belongs to the stream's group: every worker on a group must use the same one. The renewal interval is at most a third of it, so a worker misses two renewals before another may claim its task. This crate's claim step sends XAUTOCLAIM <stream> <group> <consumer> <threshold> <cursor> COUNT <n>, with <n> the worker's free slots. The cursor starts at 0-0, and each claim carries on from the cursor the last one returned. A scan that reaches the end of the pending list returns 0-0, so the next claim starts again from the beginning and an entry that became claimable behind the cursor is claimed on a later pass; a failed claim also starts over at 0-0. When a claim takes entries, the worker runs them and claims again before it reads; only a claim that takes none lets it read new entries. Every entry taken, claimed or read, has its delivery count checked before it runs.

Release. A worker may release a task it holds rather than leave it to the claim threshold: the same atomic step as a renewal, but setting the entry's idle time to the claim threshold, so the next worker's claim takes it at once. This crate releases the tasks still running when a stop's grace runs out, and a task whose handler abandons it, at any time (Failure::abandon). Each release is followed by a claim, and each claim counts a delivery, so a task released three times reaches the delivery limit. A task that shouldn't run at all is answered with an error, never released. The release script answers released (1) or lost (0, -1), as for a renewal:

-- KEYS[1] = task stream; ARGV = group, consumer, entry id, idle ms
local p = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[3], ARGV[3], 1)
if #p == 0 then return 0 end
if p[1][2] ~= ARGV[2] then return -1 end
local c = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[2], 0, ARGV[3], 'IDLE', ARGV[4], 'JUSTID')
if #c == 0 then return 0 end
return 1

The delivery limit. Each claim counts a delivery. A task runs on deliveries 1 to 3, the contract's default limit: an entry whose delivery count is more than 3 when a worker takes it gets a max_deliveries_exceeded error result instead of another run, so a task that kills its worker can't kill them all. A worker that can't read an entry's delivery count runs it as delivery 1.

A lost group. A worker whose read finds its group gone (NOGROUP) creates it again, from 0, never from $: everything still in a task stream is unfinished work. Delivery counts start again with the new group.

Results. When a task is done, the worker adds a result to the result stream, then acknowledges and deletes the task (XACK + XDEL), in that order. A result is a flat map too:

Field Meaning
task_id The task's id; always
status Exactly success or error; always
model_type, model_id, task_name, model_name Echoed from the task, always, with unknown as above. model_name names what ran only when something ran: on a success, where it may be a fuller name than the one requested, or on a failure of a stage after the model was chosen. A task rejected before anything ran echoes the name it asked for, and a handler sets no other there
error, error_type On error: a message and a code. A worker sends error_type on every error (see Errors); a reader copes without one
worker_id, processing_ms Should be written: the worker's consumer name, and how long it took. This crate's workers write them; its readers don't require them
requested_model_name Optional
embedder_key, metadata Echoed when the task had them
anything else The output, such as result (JSON) or embedding with embedding_format

An entry with no task_id, or whose status isn't exactly success or error, isn't a result: a reader reports it to its caller as malformed, then acknowledges and deletes it, as ResultReader::read does. Leaving an entry pending is right only for a handler failure that may pass on a retry. A reader requires nothing else of a result: a missing error_type, or one it doesn't know, is a failure that won't pass on a retry, never a reason to refuse the result.

Where a result goes. A worker sends a result to its task's reply_to when that's a valid reply stream, and to its own default result stream, {kind}_results, when the task names none. When reply_to is present but not valid, the task still runs and its result goes to the default result stream, with a warning in the worker's log: a result in the wrong place can be found, and a dropped one can't. Every result is routed this way, errors included. The default result stream serves an instance with a single application: with more than one application on an instance, every producer must send reply_to and every worker must honour it. The application reads its stream with a consumer group, handles each result, then acknowledges and deletes it.

Results are at least once. A crash between writing a result and acknowledging the task repeats the result rather than losing it, and XACK doesn't check the owner, so a worker that lost its lease without noticing (it stalled for a whole claim threshold after its last renewal) can still write a result and acknowledge. A consumer of results must be idempotent per task_id.

The fast lane carries tasks a caller waits for: a task stream of its own, {kind}_tasks:fast, a reply key per task, results:{app}:{kind}:rpc:{task_id}, and a deadline. Fast lane below has its rules.

Lengths and characters. A producer keeps to every rule in this table. A worker answers a task without running it only for its delivery count, its version, or what makes it unreadable, as above: a missing or empty required field, a task_id outside its rule, a repeated name, a field name or value that isn't UTF-8, or the size bounds. The other rules here are a producer's, or are checked where the value names a key:

What Rule
task_id ^[A-Za-z0-9_-]{1,64}$
model_type, model_id, task_name 1 to 256 bytes from a producer; a worker reads any non-empty value and answers unknown for one over 256 bytes
Application name (source, {app}) 1 to 32 lowercase [a-z0-9_-] from a producer and in a fast reply key; a worker reads any non-empty source; a bulk reply_to also admits upper case in {app}
Bulk reply_to ^results:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$, at most 128 bytes; any other is replaced by the default result stream
Kind ({kind}) ^[a-z0-9_-]{1,16}$
Fast reply key results:{app}:{kind}:rpc:{task_id} exactly, at most 128 bytes. Whether its {app} equals the task's source isn't compared in version 1
Payload field names, from a producer [a-z_][a-z0-9_]*, at most 64 bytes, and not reserved; a reader takes any name of up to 256 bytes
deadline_ms A plain decimal integer of Unix milliseconds: digits only. A worker takes one it can't read as no deadline

A worker also bounds what it reads: Limits refuses an entry with more than 256 fields, a field name over 256 bytes, or more than 64 MiB of names and values together. The bounds apply once Redis has delivered the entry: they keep a hostile entry from a handler and off a result stream, not out of memory.

A key prefix. A deployment may put a constant prefix in front of every key; many frameworks prefix every key of a connection. Every party on the instance then uses the same prefix. Names inside entries, such as reply_to, are always written without it, and whoever touches Redis adds it. Group names and consumer names are never prefixed. The default is no prefix. With this crate, RedisStreams::open(url)?.with_key_prefix("app_") adds it to every key a command names and to KEYS[1] of both scripts, and nothing else.

Security model

Every party that can write to the Redis instance is trusted. Nothing in the contract binds a reply to its caller or a task to its sender:

  • Any writer can name another application's reply_to on a bulk task, and neither source nor the key's {app} is checked against the connection that wrote it.
  • A fast reply isn't authenticated: anyone who can write to the instance and learns or reuses a task_id can write a reply to its key.

The control is the instance's access rules (ACLs), not the envelope. Don't expose the Redis to untrusted writers. Give producers no read access to task streams, so a task_id stays as good as a reply token, and let each application write only its own task fields and read only its own result keys.

Credentials in payloads. A payload may carry a URL with a credential in it, such as a presigned audio_url. A worker never logs payload values. This crate's own logs carry ids, stream and consumer names and the kinds of errors, never a field's value, and a Task's Debug shows its field names, never their values; a handler should keep to the same rule.

A worker

use legit_streams::{Context, Failure, RedisStreams, Reply, Task, Worker, WorkerConfig};

fn length(task: &Task, context: &Context) -> Result<Reply, Failure> {
    // The kind's required payload; without it the task is `invalid_task`...
    let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
    if !task.model_name().is_empty() && task.model_name() != "example/length" {
        return Err(Failure::new("unsupported_model", format!("no model `{}`", task.model_name()))
            .field("supported_models", "[\"example/length\"]"));
    }
    context.checkpoint()?;
    Ok(Reply::new().field("result", text.len().to_string()))
}

fn main() -> legit_streams::Result<()> {
    let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
    let config = WorkerConfig {
        concurrency: 4,
        ..WorkerConfig::new("length_tasks", "length_workers", "length-worker-host1_4242", "length_results")
    };
    let running = Worker::new(config, streams, length)?.spawn()?;

    // Stop on a signal or when the work runs out; here, after a minute...
    std::thread::sleep(std::time::Duration::from_secs(60));
    running.stop();
    let report = running.join()?;
    println!("{} results, {} released", report.results, report.released.len());
    Ok(())
}

examples/worker.rs is a fuller worker of the same kind: cargo run --example worker.

The handler runs on a thread of its own per task, up to concurrency at once. A panic is caught and answered with an internal error; one bad task never stops the loop. A long handler can call context.checkpoint()? between stages to return early when the worker is stopping or has lost the lease.

A handler that returns Failure::abandon has its task released, as above: this crate's feature, allowed at any time, and counted against the task's delivery limit by the claim that follows.

On stop, the worker takes no new task and waits up to shutdown_grace for the tasks it runs. Any still running are released, and their late results are discarded. A released task can be claimed at once by another worker while the first handler is still running. A worker that releases or abandons a task should stop working on it, and context.checkpoint() is how a long handler notices it has been released; where the work can't be interrupted, the task may run in two places at once, which at-least-once delivery already requires a handler to tolerate. The worker then removes its consumer from the group if it owns nothing. Nothing is left that only an operator could recover.

Settings

WorkerConfig field Default What it does
stream, group, consumer, result_stream (given) Where tasks come from, who reads them, where results of tasks without a valid reply_to go
route_results_per_app true Send a result to its task's valid reply_to; off, every result goes to result_stream. Turn it off only on an instance with a single application
concurrency 1 Tasks run at once; each claim and read takes at most the slots free
read_block 5 s How long one read waits; also the longest a stop waits for a read
lease_heartbeat 60 s How often each running task's lease is renewed; at most a third of claim_idle
claim_idle 300 s The group's claim threshold; the same on every worker of the group
max_deliveries 3 The last delivery a task runs on; past it, max_deliveries_exceeded
shutdown_grace 30 s How long a stop waits for running tasks before releasing them
flush_attempts, flush_backoff 5, 2 s Retries for writing a result and acknowledging, with a growing wait
limits see above Bounds on a task read and a result written

A producer and a result reader

use std::time::Duration;
use legit_streams::{Error, Producer, RedisStreams, ResultReader, Task};

fn main() -> legit_streams::Result<()> {
    let streams = RedisStreams::open("redis://127.0.0.1:6379")?;

    let task = Task::builder("app", "post", "42")
        .model_name("example/length")
        .reply_to(legit_streams::reply_to("app", "length"))
        .field("text_data", "Where is the station?")
        .build()?;
    match Producer::new(streams.clone(), "length_tasks").send(&task) {
        Ok(id) => println!("sent {} as entry {id}", task.task_id()),
        Err(Error::StreamFull { depth, .. }) => println!("{depth} tasks waiting; try again later"),
        Err(error) => return Err(error),
    }

    let reader = ResultReader::new(streams, "results:app:length", "app", "app-host1");
    for received in reader.read(25, Some(Duration::from_secs(5)))? {
        match &received.result {
            Ok(result) if result.is_success() => println!("{}: {:?}", result.task_id(), result.get("result")),
            Ok(result) => println!("{} failed: {:?} {:?}", result.task_id(), result.error_type(), result.error()),
            Err(error) => println!("entry {} isn't a result: {error}", received.id),
        }
        reader.ack(&[received.id])?;
    }
    // Results a crashed reader left unacknowledged for five minutes, each with its delivery count...
    for stranded in reader.reclaim(Duration::from_secs(300), 25)? {
        println!("entry {} delivered {:?} times", stranded.id, stranded.deliveries);
    }
    Ok(())
}

examples/producer.rs sends three tasks and reads their results: cargo run --example producer.

Producer::send checks the stream's length first and refuses with Error::StreamFull at the target depth, 300 by default, the contract's reference value: inline payloads make a stream's depth its memory use. The check and the add are two commands, so producers sending at once can pass the depth by a few tasks: it's a brake, not a hard cap.

Only TaskBuilder::build enforces the producer's rules. Producer::send sends a task it was given as it is: a task read from a stream rather than built keeps every field it has, reserved names included, as the contract requires of a task put back on a stream. Only a task being built must not use a reserved name.

A reader's two rules. A reader should bound how many times it retries one result, using the entry's delivery count, and set aside one that keeps failing: Received::deliveries is 1 from ResultReader::read, and the count after the claim from ResultReader::reclaim. And a reader should apply a result only to a task it issued: any writer to the instance can name its stream, and a result can be repeated.

A reader that stops. A process that stops cleanly should delete its consumer from the group, and must first check that the consumer owns no pending entries. ResultReader has no call for it: on the same Streams, call Streams::xpending_consumer(stream, group, consumer, 1) and, when it returns nothing, Streams::xgroup_delconsumer(stream, group, consumer), as the workers do when they stop.

Fast lane

The bulk lane suits work nobody waits for: a task may sit behind others, or behind a machine starting up. The fast lane is for small tasks a caller waits for, such as hashing a text as it's written or checking a distance while a user waits for a page. A caller sends a task with a reply key of its own and a deadline, and blocks on that key; a fast worker, serving no other stream, answers on it.

Each fast lane has a kind, which names its reply keys. The kind is a required setting of both the worker and the caller: a worker answers only reply keys of its own kind.

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

fn main() -> legit_streams::Result<()> {
    let streams = RedisStreams::open("redis://127.0.0.1:6379")?;

    // The worker, on a host that serves the lane...
    let consumer = legit_streams::fast_consumer_name("length-worker-host1", std::process::id());
    let config = FastWorkerConfig {
        concurrency: 4,
        ..FastWorkerConfig::new("length_tasks:fast", "length_workers", consumer, "length")
    };
    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()))
    })?
    .spawn()?;

    // ...and a caller, in the application.
    let caller = FastCaller::new(streams, "length_tasks:fast", "length");
    let task = Task::builder("app", "query", "0").field("text_data", "Where is the station?").build()?;
    match caller.call(&task, Duration::from_secs(3)) {
        Ok(result) if result.is_success() => println!("{:?}", result.get("result")),
        Ok(result) => println!("failed: {:?}", result.error()),
        Err(Error::Timeout { .. }) => println!("no answer in time; using the slow path"),
        Err(error) => return Err(error),
    }

    running.stop();
    running.join()?;
    Ok(())
}

examples/fast.rs runs both: cargo run --example fast.

The request is a task on the fast task stream with two more fields, which FastCaller::call sets:

Field Meaning
reply_to The task's reply key, results:{app}:{kind}:rpc:{task_id}, with {app} the task's source
deadline_ms Optional: the Unix time in milliseconds after which the caller no longer waits; the caller's clock plus its timeout

A fast task's task_id must carry at least 64 random bits: the reply key is named after it, and an id another party can guess is a key it can answer. The builder's generated {app}_{ULID} id does; a caller that sets its own id with TaskBuilder::task_id owns that.

The reply key is a stream of its own, which only this task's result goes to. A worker answers only when reply_to is exactly results:{app}:{kind}:rpc:{task_id} for the task's own task_id and the worker's own kind, within the lengths and characters above; it acknowledges and deletes any other task unanswered. The reply is a result as the bulk lane writes it. The worker adds it, then sets the key to expire 60 s later, then acknowledges and deletes the task. The caller reads the key from its start (XREAD … STREAMS <key> 0), so a reply that came before the read is still seen, and then deletes it. A reply whose caller gave up expires with its key.

The deadline is a plain decimal integer of Unix milliseconds. It's checked when the worker reads the task, against the worker's clock, with no tolerance: strictly past it, the task is acknowledged and deleted without running, since its caller has given up; a worker whose clock reads exactly the deadline still answers. Caller and worker clocks must agree to well within a timeout. A missing, empty or unreadable deadline_ms (a sign, a point, an exponent, a blank) is no deadline. The deadline isn't checked again after the work: a task that finishes late is still answered, and its reply expires unread.

The worker's order for each fast task: first the reply key (a bad one: the task is removed, unanswered), then the deadline (past: removed, unanswered), and every other task gets exactly one result, success or error. A task the worker can't serve gets an error result, not silence. A reply that can't be written isn't tried again, and the task is still removed.

The caller reads its key from 0 and takes a reply only when it's a result whose task_id is the task's own and whose status is exactly success or error. It hands a reply of either status to the application as it was written: an error reply is an answer, and the application decides what to do with it. Anything else on the key isn't a reply. A caller should read past it and keep waiting until its timeout, as this crate's caller does, so a genuine reply that arrives after a stray entry is still taken; a caller may instead give up at the first. Either way a stray entry alone ends as a timeout, never as a result. Once it has a reply, the caller deletes the key.

On a timeout call returns Error::Timeout, having deleted its task from the stream, so no worker starts it, and its reply key. Nothing is left to wait for: the caller falls back, to a slower path or an error for its user. It doesn't send the task again, since its deadline has passed.

The worker reads with a consumer group, as the bulk lane does, but never claims, leases, releases or retries: a fast task is answered once or not at all. An error, a panic or an envelope that isn't a task gets an error result, as in the bulk lane. A handler that abandons its task, and a task no thread could be started for, get an internal error result, so the caller falls back at once rather than at its timeout. A worker asked to stop reads no more and answers what it has read, however long that takes, since a caller may still be waiting; a handler that checks context.checkpoint() once the worker is stopping returns early, and its task is answered with an internal error. A fast worker runs on threads of its own, so a process can run one beside a bulk Worker on the same connection pool: a bulk task holds a bulk slot, never a fast one, and the fast lane is never queued behind bulk work.

Any consumer name unique within the group works for a fast worker. This crate's helper, fast_consumer_name, gives <prefix>-fast_<pid>, which keeps a host's fast consumer beside its bulk one in a listing.

FastWorkerConfig field Default What it does
stream, group, consumer (given) Where tasks come from, and who reads them
kind (given) The lane's kind, the {kind} of the reply keys it answers
concurrency 1 Tasks run at once, each on a thread of its own; also the most one read takes
read_block 1 s How long one read waits; also the longest a stop waits for a read
reply_ttl 60 s How long a reply key lives after a reply; whole seconds
limits see above Bounds on a task read and a result written

What an operator does for the lane. A fast entry left pending, because its worker died or couldn't acknowledge it, is never run again, and nothing in this crate removes it. An operator, or a separate control plane, deletes fast entries older than a limit, 120 s as the reference value, pending or not, and counts them; it never sends them again, since no caller waits any more. It also alerts when the lane holds entries and no fast consumer has read for a while, because then every caller is falling back, and it keeps the lane out of any measure of bulk demand: a fast backlog means the fast workers are down, not that more bulk capacity is needed.

Errors

The result error types the contract names, which a handler returns with Failure::new and a reader sees in error_type:

error_type When
unsupported_model The worker doesn't serve the requested model or method; it never substitutes another. Add supported_models
model_unavailable The worker serves the model but can't run it now. Add unavailable_reason, and retry_after_s when a retry may succeed
invalid_dimensions An output width the model can't give. Add dimensions_requested and supported_dimensions
invalid_embed_role embed_role is neither query nor passage
invalid_options A payload option is malformed
download_failed, url_expired A payload given by reference couldn't be fetched; url_expired when the URL's credential was refused
decode_failed The payload was fetched or received but couldn't be decoded, for any kind of task
diarize_failed, asr_failed A stage of an audio task failed
result_too_large The handler's successful reply is over the worker's limits (the worker sets it). A handler's error over them keeps its own code, its echoes and fields dropped as a refusal's are
max_deliveries_exceeded Delivered more than the limit (the worker sets it), or set aside by whoever operates the Redis instance, who may write this result too; its error text should say which
invalid_task The envelope couldn't be read (the worker sets it), or the kind's required payload is missing (the handler sets it)
unsupported_version The task's v is present and isn't 1 (the worker sets it)
internal The handler panicked or returned an unusable reply, such as an error type that isn't lowercase snake case, or a fast task was abandoned or couldn't be started (the worker sets it)

Error types are an open set in lowercase snake case. The crate has a constant for each above, such as legit_streams::UNSUPPORTED_MODEL, and keeps them as strings: a reader treats a code it doesn't know, or none, as a failure that won't pass on a retry, and never refuses the result for it.

The crate's own Error, from every fallible call:

Variant When
Redis The server refused a command or couldn't be reached; never shows the URL's password
UnexpectedReply The server answered with a shape the crate can't read
NoGroup The consumer group doesn't exist
MissingField, EmptyField An envelope lacks a required field, or has an empty one that mustn't be
DuplicateField An envelope names a field twice
InvalidUtf8 A field name or value isn't UTF-8
UnsupportedVersion A task's v isn't 1
InvalidValue A value outside the contract's rules: a task_id outside its rule, a source, identity field, reply_to or field name a producer may not send, a fast lane kind that can't name a reply key, a result status other than exactly success or error, or an error type a worker would write that isn't lowercase snake case
ReservedField A builder was given an extra field named like an envelope field, or with a reserved name
TooLarge An entry over its Limits
InvalidEntryId An id that isn't <ms>-<seq>
StreamFull The task stream is at the producer's target depth
InvalidConfig Settings that can't work, such as a heartbeat over a third of the claim threshold, or a task stream named results:… or dead:…
Thread A worker thread couldn't be started
Timeout A fast-lane call got no reply in time; fall back

Compatibility

The wire format is the contract's version 1, named by a task's v field. A worker built on this crate reads version 1, and a task without v, and answers any other with unsupported_version.

The crate's Rust API may still change before 1.0; a release that changes it says so. No type of the redis crate appears in the public API: RedisStreams takes a URL and reports failures as this crate's Error, so a change of redis version is not by itself a breaking change here. Streams is a public trait with required methods; an implementation outside this crate may need new methods in a later release.

What it doesn't do

It doesn't start or stop machines, watch stream depth, trim streams, set aside poison tasks or expire old entries: an operator or a separate control plane does that, and the worker only keeps its own entries claimable. The one expiry it sets is on a fast reply key. It doesn't interpret payloads or results: what a task means is the handler's business.

Testing

MemoryStreams runs exactly the stream commands the crate sends, in memory, with the semantics Redis 7 and newer give them; its lease renewal and release are one step under one lock, as the server runs a script. On a Clock::manual, entry ids, idle times, key expiry and blocking reads follow a time only the test moves, and Clock::advance moves it one due timer at a time, letting the worker's read loop and lease heartbeat finish each step, so lease expiry, idle claims and delivery counts are tested to the millisecond:

use std::time::Duration;
use legit_streams::{Clock, EntryId, MemoryStreams, Streams};

fn main() -> legit_streams::Result<()> {
    let clock = Clock::manual(1_700_000_000_000);
    let streams = MemoryStreams::with_clock(clock.clone());
    streams.xgroup_create("hash_tasks", "hash_workers")?;
    let id = streams.xadd("hash_tasks", &[(b"task_id".as_slice(), b"app_1".as_slice())])?;
    streams.xreadgroup("hash_tasks", "hash_workers", "worker-a", 1, None)?;

    clock.advance(Duration::from_secs(300));
    let claim = streams.xautoclaim("hash_tasks", "hash_workers", "worker-b", Duration::from_secs(300), EntryId::ZERO, 1)?;
    assert_eq!(claim.claimed[0].id, id);
    Ok(())
}

The crate's tests run on the double. Before release, every command the crate issues, the lease renewal and release scripts included, and the XINFO GROUPS of Streams::group_backlog after adds, reads, acknowledgements and a claim, was run against the in-memory double and a Redis 8.0.5 server and gave identical answers, with no key prefix and with one; every worker and fast-lane scenario of the test suite passed against that server too, in both runs. It hasn't been run against Redis 6.2. On one machine, with server and client together, a fast-lane call to a handler that answers at once took a median of about 0.2 ms and under 0.5 ms at the 99th percentile, over 10,000 calls; a round trip measures the client, the server and the machine together, so expect other numbers elsewhere. The double always knows a group's lag, where a server answers nil once entries the group hasn't read have been deleted.

Changes

0.1.3

A handler's own error result over the worker's limits now keeps its error_type, with its echoes and fields dropped as a refusal's are; only a successful reply over the limits becomes result_too_large. A reader that used to see result_too_large for an oversized error now sees the handler's own code, such as invalid_options.

0.1.2

Documentation only: who may write a max_deliveries_exceeded result.

0.1.1

Streams::group_backlog, a consumer group's backlog on a task stream, and Context::elapsed.

0.1.0

The first release.

Credits

redis-rs is the client under RedisStreams. General job queues for Rust, such as apalis, store jobs in formats of their own; this crate exists to speak one existing cross-language contract field for field.

License

MIT. See LICENSE.md.