Skip to main content

legit_streams/
lib.rs

1//! A work contract over Redis Streams: task and result envelopes, a worker loop that leases,
2//! reclaims and replies, a producer and a result reader, all testable without a server.
3//!
4//! A plain Rust library with no framework dependency and no async runtime: blocking calls and
5//! threads. It speaks an existing contract, version 1 of an envelope that a PHP producer and Python
6//! workers already exchange, so a Rust program can take part on either side. The crate's README
7//! states the contract in full: its fields, lengths, lease rules and security model.
8//!
9//! - [`Task`] and [`TaskResult`] build and read the flat string field maps of the v1 task and
10//!   result envelopes, and leave payloads to the caller.
11//! - [`Worker`] reads a task stream with a consumer group, runs each task with a [`Handler`],
12//!   renews its lease while it runs with one atomic step on the server, claims tasks that dead
13//!   workers left idle, and writes each result to the stream its task names before it
14//!   acknowledges the task.
15//! - [`Producer`] sends tasks with a depth check, and [`ResultReader`] reads an application's
16//!   results.
17//! - The fast lane, for work a caller waits for: [`FastCaller::call`] sends a task with a reply key
18//!   of its own and a deadline and blocks for the reply, and [`FastWorker`] answers it on that key,
19//!   beside a bulk [`Worker`] or on its own.
20//! - [`Streams`] is the trait behind them: [`RedisStreams`] on a server, [`MemoryStreams`] in
21//!   memory on a [`Clock`] the test moves.
22//!
23//! ```
24//! use std::time::Duration;
25//! use legit_streams::{Clock, Failure, MemoryStreams, Producer, Reply, ResultReader, Task, Worker, WorkerConfig};
26//!
27//! let clock = Clock::manual(1_700_000_000_000);
28//! let streams = MemoryStreams::with_clock(clock.clone());
29//!
30//! let task = Task::builder("app", "post", "42")
31//!     .reply_to(legit_streams::reply_to("app", "hash"))
32//!     .field("text_data", "hello")
33//!     .build()?;
34//! Producer::new(streams.clone(), "hash_tasks").send(&task)?;
35//!
36//! let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
37//! let worker = Worker::new(config, streams.clone(), |task: &Task, _: &_| {
38//!     let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
39//!     Ok(Reply::new().field("result", text.len().to_string()))
40//! })?
41//! .clock(clock.clone());
42//! let running = worker.spawn()?;
43//!
44//! let reader = ResultReader::new(streams.clone(), "results:app:hash", "app", "app-1");
45//! let received = loop {
46//!     let received = reader.read(10, None)?;
47//!     if !received.is_empty() {
48//!         break received;
49//!     }
50//!     std::thread::sleep(Duration::from_millis(1));
51//! };
52//! let result = received[0].result.as_ref().expect("a valid result");
53//! assert_eq!(result.task_id(), task.task_id());
54//! assert_eq!(result.get("result"), Some("5"));
55//! reader.ack(&[received[0].id])?;
56//!
57//! running.stop();
58//! clock.advance(Duration::from_secs(5));
59//! running.join()?;
60//! # Ok::<(), legit_streams::Error>(())
61//! ```
62
63#![forbid(unsafe_code)]
64
65mod client;
66mod clock;
67mod entry;
68mod error;
69mod fast;
70mod fields;
71mod memory;
72mod redis_streams;
73mod result;
74mod streams;
75mod task;
76mod worker;
77
78pub use client::{DEFAULT_TARGET_DEPTH, Producer, Received, ResultReader};
79pub use clock::Clock;
80pub use entry::{AutoClaim, Entry, EntryId, GroupBacklog, LostLease, Pending, RawFields, Renewal};
81pub use error::{Error, Result};
82pub use fast::{
83    FastCaller, FastWorker, FastWorkerConfig, KIND_MAX_LEN, fast_consumer_name, is_valid_kind, is_valid_rpc_reply_to,
84    rpc_reply_to,
85};
86pub use fields::Limits;
87pub use memory::MemoryStreams;
88pub use redis_streams::RedisStreams;
89pub use result::{ResultBuilder, Status, TaskResult};
90pub use streams::Streams;
91pub use task::{
92    APP_MAX_LEN, FIELD_NAME_MAX_LEN, IDENTITY_MAX_LEN, REPLY_TO_MAX_LEN, RESERVED_FIELDS, TASK_ID_MAX_LEN, Task,
93    TaskBuilder, UNKNOWN, VERSION, is_valid_app, is_valid_reply_to, is_valid_task_id, reply_to, task_id,
94};
95/// The README's examples, compiled as doctests; the ones that need a server don't run.
96#[cfg(doctest)]
97#[doc = include_str!("../README.md")]
98struct ReadmeDoctests;
99
100pub use worker::{
101    ASR_FAILED, Context, DECODE_FAILED, DIARIZE_FAILED, DOWNLOAD_FAILED, Failure, Handler, INTERNAL,
102    INVALID_DIMENSIONS, INVALID_EMBED_ROLE, INVALID_OPTIONS, INVALID_TASK, MAX_DELIVERIES_EXCEEDED, MODEL_UNAVAILABLE,
103    RESULT_TOO_LARGE, Reply, Report, Running, Stopper, UNSUPPORTED_MODEL, UNSUPPORTED_VERSION, URL_EXPIRED, Worker,
104    WorkerConfig,
105};