legit-streams 0.1.4

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
//! A worker for a made-up kind of task, `length`: it reads `length_tasks` with the group
//! `length_workers` and answers each task with the length of its `text_data`.
//!
//! `cargo run --example worker` runs it on the in-memory double, with no server: it adds three
//! tasks itself, as a producer would, prints their results, and stops.
//!
//! With `REDIS_URL` set, such as `REDIS_URL=redis://127.0.0.1:6379 cargo run --example worker`,
//! it serves `length_tasks` on that server for a minute and then stops cleanly, releasing anything
//! still running. Send it tasks from another terminal with the `producer` example and the same
//! `REDIS_URL`; the producer prints the results.

use std::sync::Arc;
use std::time::{Duration, Instant};

use legit_streams::{
    Context, Failure, MemoryStreams, Producer, RedisStreams, Reply, ResultReader, Streams, Task, Worker, WorkerConfig,
};

/// The one model this worker serves.
const MODEL: &str = "example/length";

/// The handler: the length of the task's text.
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() != MODEL {
        return Err(
            Failure::new("unsupported_model", format!("no model `{}`", task.model_name()))
                .field("supported_models", format!("[\"{MODEL}\"]")),
        );
    }
    // A long handler checks in between stages, to stop early when the worker stops or the lease
    // is lost...
    context.checkpoint()?;
    Ok(Reply::new().field("result", format!("{} bytes", text.len())))
}

fn main() -> legit_streams::Result<()> {
    let url = std::env::var("REDIS_URL").ok();
    let streams: Arc<dyn Streams> = match &url {
        Some(url) => Arc::new(RedisStreams::open(url)?),
        None => Arc::new(MemoryStreams::new()),
    };

    let config = WorkerConfig {
        concurrency: 2,
        read_block: Duration::from_millis(500),
        ..WorkerConfig::new(
            "length_tasks",
            "length_workers",
            format!("length-worker-example_{}", std::process::id()),
            "length_results",
        )
    };
    let running = Worker::new(config, Arc::clone(&streams), length)?.spawn()?;

    if url.is_some() {
        println!("Serving `length_tasks` for 60 s. Run the `producer` example with the same REDIS_URL to send tasks.");
        std::thread::sleep(Duration::from_secs(60));
    } else {
        // No server: send three tasks as a producer would, and read their results...
        let producer = Producer::new(Arc::clone(&streams), "length_tasks");
        for (text, model) in [
            ("Where is the station?", ""),
            ("Bonjour", MODEL),
            ("Hello", "other/model"),
        ] {
            let task = Task::builder("app", "post", "42")
                .model_name(model)
                .reply_to(legit_streams::reply_to("app", "length"))
                .field("text_data", text)
                .build()?;
            producer.send(&task)?;
        }
        let reader = ResultReader::new(Arc::clone(&streams), "results:app:length", "app", "app-example");
        let (mut read, started) = (0, Instant::now());
        while read < 3 && started.elapsed() < Duration::from_secs(10) {
            for received in reader.read(10, Some(Duration::from_millis(100)))? {
                match &received.result {
                    Ok(result) if result.is_success() => {
                        println!("{}: {}", result.task_id(), result.get("result").unwrap_or_default());
                    }
                    Ok(result) => println!(
                        "{} failed: {} {}",
                        result.task_id(),
                        result.error_type().unwrap_or_default(),
                        result.error().unwrap_or_default()
                    ),
                    Err(error) => println!("entry {} isn't a result: {error}", received.id),
                }
                reader.ack(&[received.id])?;
                read += 1;
            }
        }
    }

    running.stop();
    let report = running.join()?;
    println!("The worker wrote {} results.", report.results);
    Ok(())
}