Skip to main content

Crate legit_streams

Crate legit_streams 

Source
Expand description

A work contract over Redis Streams: task and result envelopes, a worker loop that leases, reclaims and replies, a producer and a result reader, all testable without a server.

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. The crate’s README states the contract in full: its fields, lengths, lease rules and security model.

  • Task and TaskResult build and read the flat string field maps of the v1 task and result envelopes, and leave payloads to the caller.
  • Worker reads a task stream with a consumer group, runs each task with a Handler, renews its lease while it runs with one atomic step on the server, claims tasks that dead workers left idle, and writes each result to the stream its task names before it acknowledges the task.
  • Producer sends tasks with a depth check, and ResultReader reads an application’s results.
  • The fast lane, for work a caller waits for: FastCaller::call sends a task with a reply key of its own and a deadline and blocks for the reply, and FastWorker answers it on that key, beside a bulk Worker or on its own.
  • Streams is the trait behind them: RedisStreams on a server, MemoryStreams in memory on a Clock the test moves.
use std::time::Duration;
use legit_streams::{Clock, Failure, MemoryStreams, Producer, Reply, ResultReader, Task, Worker, WorkerConfig};

let clock = Clock::manual(1_700_000_000_000);
let streams = MemoryStreams::with_clock(clock.clone());

let task = Task::builder("app", "post", "42")
    .reply_to(legit_streams::reply_to("app", "hash"))
    .field("text_data", "hello")
    .build()?;
Producer::new(streams.clone(), "hash_tasks").send(&task)?;

let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
let worker = Worker::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());
let running = worker.spawn()?;

let reader = ResultReader::new(streams.clone(), "results:app:hash", "app", "app-1");
let received = loop {
    let received = reader.read(10, None)?;
    if !received.is_empty() {
        break received;
    }
    std::thread::sleep(Duration::from_millis(1));
};
let result = received[0].result.as_ref().expect("a valid result");
assert_eq!(result.task_id(), task.task_id());
assert_eq!(result.get("result"), Some("5"));
reader.ack(&[received[0].id])?;

running.stop();
clock.advance(Duration::from_secs(5));
running.join()?;

Structs§

AutoClaim
What XAUTOCLAIM returns.
Clock
The time a Worker and a MemoryStreams run on: the system’s, or a manual clock that only a test moves.
Context
What a handler can ask about the task it runs and the worker running it.
Entry
A stream entry: its id and its raw fields.
EntryId
The id Redis gives a stream entry, <milliseconds>-<sequence>. Ids order entries by when they were added.
Failure
What a Handler returns for a task that failed: an error result, or, with Failure::abandon, no result at all and the task left to another worker.
FastCaller
Sends fast-lane tasks and waits for their replies.
FastWorker
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:
FastWorkerConfig
The settings of a FastWorker.
GroupBacklog
How much work a consumer group hasn’t finished, as XINFO GROUPS reports it: what Streams::group_backlog returns.
Limits
The bounds an envelope checks before it reads an entry’s fields. An entry over any of them is refused with Error::TooLarge.
MemoryStreams
The stream commands of Streams run in memory, with the semantics Redis 7 gives them, on a Clock the test controls: entry ids, idle times and blocking reads follow its time, so lease expiry, idle claims and delivery counts can be tested to the millisecond.
Pending
One entry of a consumer group’s pending entries list, as XPENDING reports it.
Producer
Sends tasks to a task stream, checking its depth first: a stream at or over the target depth takes no more until workers drain it, because inline payloads make the stream’s depth its memory use.
Received
A result read from a reply stream: its entry id, the result, or why the entry isn’t one, and how many times the entry has been delivered.
RedisStreams
Streams on a Redis server, 6.2 or newer, over blocking connections.
Reply
What a Handler returns for a task that succeeded: the fields of its output, which the worker adds to the result after the envelope’s own.
Report
What a worker did before it stopped.
ResultBuilder
A result being built. ResultBuilder::build writes the fields in this order: task_id, model_type, model_id, task_name, model_name, status, error_type, error, worker_id and processing_ms, each when set, then the extra fields in the order they were added. The contract doesn’t fix an order; this one is the crate’s.
ResultReader
Reads an application’s results from its reply stream with a consumer group: read, handle, then ResultReader::ack, which acknowledges and deletes. An entry left unacknowledged stays pending, and ResultReader::reclaim takes it back once idle, so a reader that crashes between storing a result and acknowledging it loses nothing.
Running
A worker running on a thread of its own, from Worker::spawn.
Stopper
Asks a running Worker to stop. Cheap to clone.
Task
A v1 task envelope: the flat map of string fields a producer adds to a task stream.
TaskBuilder
A task being built; TaskBuilder::build writes the fields in this order, which is the crate’s (a reader takes the fields as a map): task_id, model_type, model_id, task_name, model_name, source, v, reply_to when set, then the extra fields in the order they were added.
TaskResult
A result envelope: the flat map of string fields a worker adds to a reply stream.
Worker
The worker side of the contract. It reads tasks from a stream with a consumer group, runs each with a Handler and writes the result to the reply stream, then acknowledges and deletes the task:
WorkerConfig
The settings of a Worker. The defaults are the contract’s reference values, where it gives one; a deployment may change them. What the contract fixes is that the heartbeat is at most a third of the claim threshold and that every worker on a group uses the same threshold.

Enums§

Error
What went wrong. Every failure in this crate, hostile input included, is one of these; nothing panics on what a stream holds.
LostLease
Why a lease was lost. A worker treats both the same: it writes no result and leaves the entry alone. The two are kept apart for log lines.
Renewal
What Streams::renew_lease found.
Status
Whether a task succeeded, the result’s status field.

Constants§

APP_MAX_LEN
The longest application name a producer sends, the task’s source and the {app} of its reply streams, in bytes. A worker reading a task takes any non-empty source.
ASR_FAILED
The error type of an audio task whose transcription failed.
DECODE_FAILED
The error type of a task whose payload was fetched or received but couldn’t be decoded, for any kind of task.
DEFAULT_TARGET_DEPTH
The target depth a Producer starts with, the contract’s reference value; a deployment may choose another with Producer::target_depth.
DIARIZE_FAILED
The error type of an audio task whose speaker separation failed.
DOWNLOAD_FAILED
The error type of a task whose payload, given by reference, couldn’t be fetched.
FIELD_NAME_MAX_LEN
The longest payload field name a producer sends, in bytes. A name is lowercase ASCII letters, digits and _, not starting with a digit; a reader accepts any name within its Limits.
IDENTITY_MAX_LEN
The longest model_type, model_id and task_name a producer sends, in bytes. A worker that reads a longer one still runs the task, and answers with UNKNOWN in its place.
INTERNAL
The error type of a task whose handler panicked or returned an unusable reply.
INVALID_DIMENSIONS
The error type of a task that asks for an output width the model can’t give; add dimensions_requested and supported_dimensions fields.
INVALID_EMBED_ROLE
The error type of a task whose embed_role is neither query nor passage.
INVALID_OPTIONS
The error type of a task with a malformed payload option. A missing required payload is INVALID_TASK instead.
INVALID_TASK
The error type of an entry the worker can’t read as a task, and of a task whose kind’s required payload is missing.
KIND_MAX_LEN
The longest kind of a fast lane, the {kind} of its reply keys, in bytes.
MAX_DELIVERIES_EXCEEDED
The error type of a task delivered more than WorkerConfig::max_deliveries times.
MODEL_UNAVAILABLE
The error type of a task for a model the worker serves but can’t run now; add an unavailable_reason field, and retry_after_s when a retry may succeed.
REPLY_TO_MAX_LEN
The longest reply_to, in bytes: a bulk reply stream and a fast-lane reply key alike.
RESERVED_FIELDS
The payload field names a producer may not use: any name starting with _, and these two. 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 worker passes them through untouched.
RESULT_TOO_LARGE
The error type of a task whose handler’s reply is over the worker’s Limits. A task the worker refuses keeps its own error type, such as INVALID_TASK, whatever it echoes.
TASK_ID_MAX_LEN
The longest task_id, in bytes. A task id is 1 to 64 ASCII letters, digits, _ and -.
UNKNOWN
What a worker writes in a result’s model_type, model_id or task_name when the task’s was missing, empty, or longer than IDENTITY_MAX_LEN. A result’s model_name is never replaced.
UNSUPPORTED_MODEL
The error type of a task that asks for a model or method the worker doesn’t serve; add a supported_models field. A worker never substitutes another model.
UNSUPPORTED_VERSION
The error type of a task whose v is present and isn’t 1. The worker doesn’t run it.
URL_EXPIRED
The error type of a task whose payload, given by reference, couldn’t be fetched because the URL’s credential was refused, such as an expired presigned URL.
VERSION
The envelope version this crate reads and writes, the value of every task’s v field.

Traits§

Handler
Runs a task. A worker calls it on a thread of its own for each task, so it must be Sync; a closure Fn(&Task, &Context) -> Result<Reply, Failure> is one.
Streams
The Redis stream commands this crate sends, and nothing else. RedisStreams sends them to a server; MemoryStreams runs them in memory for tests.

Functions§

fast_consumer_name
A consumer name for a fast worker, <prefix>-fast_<pid>, with no - when the prefix already ends in - or _. This is the crate’s helper, not a rule of the contract: any name unique within the group works. Sharing a host’s prefix keeps a host’s consumers together in a listing, and fast keeps it apart from a bulk consumer named <prefix>_<pid>.
is_valid_app
Whether an application name is one this crate sends: 1 to APP_MAX_LEN lowercase ASCII letters, digits, _ and -. It is the form a task’s source takes from this crate’s builder, and the only one a fast-lane reply key admits. A worker reading a task requires only that its source isn’t empty.
is_valid_kind
Whether kind can name a fast lane: 1 to KIND_MAX_LEN lowercase ASCII letters, digits, _ and -, such as hash or image. A FastWorker and a FastCaller each serve one kind, and a worker answers only reply keys of its own.
is_valid_reply_to
Whether a bulk task’s reply_to keeps to the contract: it must match ^results:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$ and be at most REPLY_TO_MAX_LEN bytes. A producer sends no other. A task’s reply_to names a Redis key and comes off a queue, so a worker checks it rather than trusting it: a task whose reply_to fails still runs, and its result, success or error, goes to the worker’s default result stream, since a result in the wrong place can be found and a dropped one can’t.
is_valid_rpc_reply_to
Whether a fast worker of this kind answers a task with this reply_to and task_id: the key must be exactly rpc_reply_to(app, kind, task_id) for this task’s id and this kind, with app passing is_valid_app, task_id passing is_valid_task_id, and at most REPLY_TO_MAX_LEN bytes. Another task’s id, another kind, a bulk reply stream and trailing bytes all fail. A worker deletes a task whose key fails without answering it: a reply key comes off a queue and names a Redis key, so it’s checked rather than trusted.
is_valid_task_id
Whether a task_id keeps to the contract: 1 to TASK_ID_MAX_LEN ASCII letters, digits, _ and -. A producer sends no other, and a worker refuses any other.
reply_to
The reply stream the contract names for an application’s results of one kind, results:{app}:{modality}.
rpc_reply_to
The reply key of a fast task, results:{app}:{kind}:rpc:{task_id}: a stream of its own, which only that task’s result is added to. kind names the lane, such as hash.
task_id
Generate a task id in the form the crate gives every task it builds, {app}_{ULID}: unique across applications, and the key a result carries back. Other ids a worker accepts are any that pass is_valid_task_id.

Type Aliases§

RawFields
The raw fields of a stream entry, in the order they were added, as bytes: Redis stores bytes, and the envelopes check that they’re UTF-8.
Result
The result of a fallible operation in this crate.