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.
TaskandTaskResultbuild and read the flat string field maps of the v1 task and result envelopes, and leave payloads to the caller.Workerreads a task stream with a consumer group, runs each task with aHandler, 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.Producersends tasks with a depth check, andResultReaderreads an application’s results.- The fast lane, for work a caller waits for:
FastCaller::callsends a task with a reply key of its own and a deadline and blocks for the reply, andFastWorkeranswers it on that key, beside a bulkWorkeror on its own. Streamsis the trait behind them:RedisStreamson a server,MemoryStreamsin memory on aClockthe 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§
- Auto
Claim - What
XAUTOCLAIMreturns. - Clock
- The time a
Workerand aMemoryStreamsrun 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
Handlerreturns for a task that failed: an error result, or, withFailure::abandon, no result at all and the task left to another worker. - Fast
Caller - Sends fast-lane tasks and waits for their replies.
- Fast
Worker - 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:
- Fast
Worker Config - The settings of a
FastWorker. - Group
Backlog - How much work a consumer group hasn’t finished, as
XINFO GROUPSreports it: whatStreams::group_backlogreturns. - Limits
- The bounds an envelope checks before it reads an entry’s fields. An entry over any of them is
refused with
Error::TooLarge. - Memory
Streams - The stream commands of
Streamsrun in memory, with the semantics Redis 7 gives them, on aClockthe 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
XPENDINGreports 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.
- Redis
Streams Streamson a Redis server, 6.2 or newer, over blocking connections.- Reply
- What a
Handlerreturns 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.
- Result
Builder - A result being built.
ResultBuilder::buildwrites the fields in this order:task_id,model_type,model_id,task_name,model_name,status,error_type,error,worker_idandprocessing_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. - Result
Reader - 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, andResultReader::reclaimtakes 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
Workerto stop. Cheap to clone. - Task
- A v1 task envelope: the flat map of string fields a producer adds to a task stream.
- Task
Builder - A task being built;
TaskBuilder::buildwrites 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_towhen set, then the extra fields in the order they were added. - Task
Result - 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
Handlerand writes the result to the reply stream, then acknowledges and deletes the task: - Worker
Config - 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.
- Lost
Lease - 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_leasefound. - Status
- Whether a task succeeded, the result’s
statusfield.
Constants§
- APP_
MAX_ LEN - The longest application name a producer sends, the task’s
sourceand the{app}of its reply streams, in bytes. A worker reading a task takes any non-emptysource. - 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
Producerstarts with, the contract’s reference value; a deployment may choose another withProducer::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 itsLimits. - IDENTITY_
MAX_ LEN - The longest
model_type,model_idandtask_namea producer sends, in bytes. A worker that reads a longer one still runs the task, and answers withUNKNOWNin 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_requestedandsupported_dimensionsfields. - INVALID_
EMBED_ ROLE - The error type of a task whose
embed_roleis neitherquerynorpassage. - INVALID_
OPTIONS - The error type of a task with a malformed payload option. A missing required payload is
INVALID_TASKinstead. - 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_deliveriestimes. - MODEL_
UNAVAILABLE - The error type of a task for a model the worker serves but can’t run now; add an
unavailable_reasonfield, andretry_after_swhen 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, andrequeue_countandrequeued_atfor 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 asINVALID_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_idortask_namewhen the task’s was missing, empty, or longer thanIDENTITY_MAX_LEN. A result’smodel_nameis 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_modelsfield. A worker never substitutes another model. - UNSUPPORTED_
VERSION - The error type of a task whose
vis present and isn’t1. 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
vfield.
Traits§
- Handler
- Runs a task. A worker calls it on a thread of its own for each task, so it must be
Sync; a closureFn(&Task, &Context) -> Result<Reply, Failure>is one. - Streams
- The Redis stream commands this crate sends, and nothing else.
RedisStreamssends them to a server;MemoryStreamsruns 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, andfastkeeps 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_LENlowercase ASCII letters, digits,_and-. It is the form a task’ssourcetakes from this crate’s builder, and the only one a fast-lane reply key admits. A worker reading a task requires only that itssourceisn’t empty. - is_
valid_ kind - Whether
kindcan name a fast lane: 1 toKIND_MAX_LENlowercase ASCII letters, digits,_and-, such ashashorimage. AFastWorkerand aFastCallereach serve one kind, and a worker answers only reply keys of its own. - is_
valid_ reply_ to - Whether a bulk task’s
reply_tokeeps to the contract: it must match^results:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$and be at mostREPLY_TO_MAX_LENbytes. A producer sends no other. A task’sreply_tonames a Redis key and comes off a queue, so a worker checks it rather than trusting it: a task whosereply_tofails 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
kindanswers a task with thisreply_toandtask_id: the key must be exactlyrpc_reply_to(app, kind, task_id)for this task’s id and this kind, withapppassingis_valid_app,task_idpassingis_valid_task_id, and at mostREPLY_TO_MAX_LENbytes. 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_idkeeps to the contract: 1 toTASK_ID_MAX_LENASCII 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.kindnames the lane, such ashash. - 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 passis_valid_task_id.