Skip to main content

legit_streams/
worker.rs

1//! The worker side of the contract: read tasks from a consumer group, run them, reply.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::panic::{self, AssertUnwindSafe};
6use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
7use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
8use std::thread::{self, JoinHandle};
9use std::time::Duration;
10
11use crate::clock::{Clock, Signal};
12use crate::entry::{Entry, EntryId, LostLease, Renewal};
13use crate::error::{Error, Result};
14use crate::fields::{self, Limits};
15use crate::result::{ResultBuilder, Status, TaskResult};
16use crate::streams::Streams;
17use crate::task::{Task, is_valid_reply_to};
18
19/// The error type of a task that asks for a model or method the worker doesn't serve; add a
20/// `supported_models` field. A worker never substitutes another model.
21///
22/// ```
23/// assert_eq!(legit_streams::UNSUPPORTED_MODEL, "unsupported_model");
24/// ```
25pub const UNSUPPORTED_MODEL: &str = "unsupported_model";
26/// The error type of a task that asks for an output width the model can't give; add
27/// `dimensions_requested` and `supported_dimensions` fields.
28///
29/// ```
30/// assert_eq!(legit_streams::INVALID_DIMENSIONS, "invalid_dimensions");
31/// ```
32pub const INVALID_DIMENSIONS: &str = "invalid_dimensions";
33/// The error type of a task with a malformed payload option. A missing required payload is
34/// [`INVALID_TASK`] instead.
35///
36/// ```
37/// assert_eq!(legit_streams::INVALID_OPTIONS, "invalid_options");
38/// ```
39pub const INVALID_OPTIONS: &str = "invalid_options";
40/// The error type of a task whose `embed_role` is neither `query` nor `passage`.
41///
42/// ```
43/// assert_eq!(legit_streams::INVALID_EMBED_ROLE, "invalid_embed_role");
44/// ```
45pub const INVALID_EMBED_ROLE: &str = "invalid_embed_role";
46/// The error type of a task for a model the worker serves but can't run now; add an
47/// `unavailable_reason` field, and `retry_after_s` when a retry may succeed.
48///
49/// ```
50/// assert_eq!(legit_streams::MODEL_UNAVAILABLE, "model_unavailable");
51/// ```
52pub const MODEL_UNAVAILABLE: &str = "model_unavailable";
53/// The error type of a task whose payload, given by reference, couldn't be fetched.
54///
55/// ```
56/// assert_eq!(legit_streams::DOWNLOAD_FAILED, "download_failed");
57/// ```
58pub const DOWNLOAD_FAILED: &str = "download_failed";
59/// The error type of a task whose payload, given by reference, couldn't be fetched because the
60/// URL's credential was refused, such as an expired presigned URL.
61///
62/// ```
63/// assert_eq!(legit_streams::URL_EXPIRED, "url_expired");
64/// ```
65pub const URL_EXPIRED: &str = "url_expired";
66/// The error type of a task whose payload was fetched or received but couldn't be decoded, for
67/// any kind of task.
68///
69/// ```
70/// assert_eq!(legit_streams::DECODE_FAILED, "decode_failed");
71/// ```
72pub const DECODE_FAILED: &str = "decode_failed";
73/// The error type of an audio task whose speaker separation failed.
74///
75/// ```
76/// assert_eq!(legit_streams::DIARIZE_FAILED, "diarize_failed");
77/// ```
78pub const DIARIZE_FAILED: &str = "diarize_failed";
79/// The error type of an audio task whose transcription failed.
80///
81/// ```
82/// assert_eq!(legit_streams::ASR_FAILED, "asr_failed");
83/// ```
84pub const ASR_FAILED: &str = "asr_failed";
85/// The error type of an entry the worker can't read as a task, and of a task whose kind's
86/// required payload is missing.
87///
88/// A worker sets it for an entry with a field of the envelope missing or empty, a `task_id` outside
89/// the rules, a name given twice, a field name or value that isn't UTF-8, or over the [`Limits`],
90/// once the entry's delivery count is within [`WorkerConfig::max_deliveries`]. It answers such an
91/// entry when its `task_id` isn't empty and is UTF-8 of at most 256 bytes, carrying the id exactly
92/// as sent, and removes it either way: with no such `task_id`, unanswered. A handler returns it for
93/// a task without the payload its kind requires, such as a text task with no `text_data`.
94///
95/// ```
96/// assert_eq!(legit_streams::INVALID_TASK, "invalid_task");
97/// ```
98pub const INVALID_TASK: &str = "invalid_task";
99/// The error type of a task whose `v` is present and isn't `1`. The worker doesn't run it.
100///
101/// ```
102/// assert_eq!(legit_streams::UNSUPPORTED_VERSION, "unsupported_version");
103/// ```
104pub const UNSUPPORTED_VERSION: &str = "unsupported_version";
105/// The error type of a task delivered more than [`WorkerConfig::max_deliveries`] times.
106///
107/// ```
108/// assert_eq!(legit_streams::MAX_DELIVERIES_EXCEEDED, "max_deliveries_exceeded");
109/// ```
110pub const MAX_DELIVERIES_EXCEEDED: &str = "max_deliveries_exceeded";
111/// The error type of a task whose handler panicked or returned an unusable reply.
112///
113/// ```
114/// assert_eq!(legit_streams::INTERNAL, "internal");
115/// ```
116pub const INTERNAL: &str = "internal";
117/// The error type of a task whose handler's reply is over the worker's [`Limits`]. A task the
118/// worker refuses keeps its own error type, such as [`INVALID_TASK`], whatever it echoes.
119///
120/// ```
121/// assert_eq!(legit_streams::RESULT_TOO_LARGE, "result_too_large");
122/// ```
123pub const RESULT_TOO_LARGE: &str = "result_too_large";
124
125/// How long the read loop waits after a failed read before it tries again.
126const READ_RETRY: Duration = Duration::from_secs(1);
127
128/// The settings of a [`Worker`]. The defaults are the contract's reference values, where it gives
129/// one; a deployment may change them. What the contract fixes is that the heartbeat is at most a
130/// third of the claim threshold and that every worker on a group uses the same threshold.
131///
132/// ```
133/// use std::time::Duration;
134/// use legit_streams::WorkerConfig;
135///
136/// let config = WorkerConfig {
137///     concurrency: 4,
138///     ..WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results")
139/// };
140/// assert_eq!(config.lease_heartbeat, Duration::from_secs(60));
141/// ```
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct WorkerConfig {
144    /// The task stream, such as `hash_tasks`. It can't begin with `results:` or `dead:`, the
145    /// names of result streams and of tasks an operator has set aside.
146    pub stream: String,
147    /// The consumer group the worker reads it with, such as `hash_workers`, created when missing.
148    pub group: String,
149    /// This worker's consumer name, unique within the group, and the `worker_id` of its results.
150    pub consumer: String,
151    /// Where the result of a task that names no valid `reply_to` goes, such as `hash_results`, and
152    /// every result when [`WorkerConfig::route_results_per_app`] is off.
153    pub result_stream: String,
154    /// Send each result to the stream its task's `reply_to` names. On by default, as the contract
155    /// asks: a worker honours a task's `reply_to`, and uses `result_stream` only for a task that
156    /// names none. A task whose `reply_to` fails [`is_valid_reply_to`] still runs, and its result,
157    /// success or error, goes to `result_stream`, with a warning in the log.
158    ///
159    /// Turn it off only on an instance with a single application: with more than one, every
160    /// producer must send `reply_to` and every worker must honour it.
161    pub route_results_per_app: bool,
162    /// How many tasks run at once, each on a thread of its own. 1 by default.
163    pub concurrency: usize,
164    /// How long one read waits for a task; also the longest a stop waits for a read in progress.
165    /// 5 s by default.
166    pub read_block: Duration,
167    /// How often the worker renews the lease on each task it runs, so no other worker claims it.
168    /// 60 s by default, the contract's reference value; at most a third of
169    /// [`WorkerConfig::claim_idle`], so a worker can miss two renewals before another claims its
170    /// task.
171    pub lease_heartbeat: Duration,
172    /// How long an entry must sit unrenewed before this worker claims it from another, presumed
173    /// dead. 300 s by default, the contract's reference value. It belongs to the group, not the
174    /// worker: every worker reading a group must use the same value, or one with a shorter
175    /// threshold claims tasks that another's heartbeat keeps alive.
176    pub claim_idle: Duration,
177    /// How many deliveries a task may have: it runs on deliveries 1 to `max_deliveries`. A task
178    /// whose delivery count is more than this when a worker takes it is answered with a
179    /// `max_deliveries_exceeded` error rather than run again. 3 by default, the contract's default.
180    pub max_deliveries: u64,
181    /// How long a stop waits for running tasks before it releases them to other workers. 30 s by
182    /// default.
183    pub shutdown_grace: Duration,
184    /// How many times the worker tries to write a result, and then to acknowledge the task, before
185    /// it leaves the task pending for another worker. 5 by default.
186    pub flush_attempts: u32,
187    /// The wait before the second attempt; each later one waits that much longer. 2 s by
188    /// default.
189    pub flush_backoff: Duration,
190    /// The bounds on a task the worker reads and a result it writes.
191    pub limits: Limits,
192}
193
194impl WorkerConfig {
195    /// The default settings for reading `stream` with `group` as `consumer`, replying to
196    /// `result_stream`.
197    ///
198    /// ```
199    /// use legit_streams::WorkerConfig;
200    ///
201    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
202    /// assert_eq!(config.concurrency, 1);
203    /// assert!(config.route_results_per_app);
204    /// assert_eq!(config.max_deliveries, 3);
205    /// ```
206    #[must_use]
207    pub fn new(
208        stream: impl Into<String>,
209        group: impl Into<String>,
210        consumer: impl Into<String>,
211        result_stream: impl Into<String>,
212    ) -> Self {
213        Self {
214            stream: stream.into(),
215            group: group.into(),
216            consumer: consumer.into(),
217            result_stream: result_stream.into(),
218            route_results_per_app: true,
219            concurrency: 1,
220            read_block: Duration::from_secs(5),
221            lease_heartbeat: Duration::from_secs(60),
222            claim_idle: Duration::from_secs(300),
223            max_deliveries: 3,
224            shutdown_grace: Duration::from_secs(30),
225            flush_attempts: 5,
226            flush_backoff: Duration::from_secs(2),
227            limits: Limits::default(),
228        }
229    }
230
231    fn validate(&self) -> Result<()> {
232        let invalid = |message: &str| Err(Error::InvalidConfig(message.to_owned()));
233        for (name, value) in [
234            ("stream", &self.stream),
235            ("group", &self.group),
236            ("consumer", &self.consumer),
237            ("result_stream", &self.result_stream),
238        ] {
239            if value.is_empty() {
240                return Err(Error::InvalidConfig(format!("`{name}` is empty")));
241            }
242        }
243        check_task_stream(&self.stream)?;
244        if self.concurrency == 0 {
245            return invalid("`concurrency` is 0; a worker runs at least one task at once");
246        }
247        if self.read_block.is_zero() {
248            return invalid("`read_block` is 0; Redis reads `BLOCK 0` as forever");
249        }
250        if self.lease_heartbeat.is_zero() || self.lease_heartbeat.saturating_mul(3) > self.claim_idle {
251            return invalid(
252                "`lease_heartbeat` must be above 0 and at most a third of `claim_idle`, so a worker can miss two \
253                 renewals before another claims its task",
254            );
255        }
256        if self.max_deliveries == 0 {
257            return invalid("`max_deliveries` is 0; a task needs one delivery to run");
258        }
259        if self.flush_attempts == 0 {
260            return invalid("`flush_attempts` is 0; a result needs one attempt to be written");
261        }
262        Ok(())
263    }
264}
265
266/// Refuse a task stream name the contract keeps for other keys: one beginning with `results:`,
267/// the result streams and reply keys, or `dead:`, tasks an operator has set aside.
268pub(crate) fn check_task_stream(stream: &str) -> Result<()> {
269    for reserved in ["results:", "dead:"] {
270        if stream.starts_with(reserved) {
271            return Err(Error::InvalidConfig(format!(
272                "the task stream `{stream}` begins with `{reserved}`, which no task stream may"
273            )));
274        }
275    }
276    Ok(())
277}
278
279/// The longest `task_id` a worker carries back on an error result for an entry it can't read, in
280/// bytes. A longer one, or one that isn't UTF-8, counts as none: the entry is removed unanswered.
281const ANSWERED_TASK_ID_MAX_LEN: usize = 256;
282
283/// The `task_id` a worker answers an unreadable entry with: the last one, exactly as sent, when it
284/// isn't empty and is UTF-8 of at most 256 bytes.
285pub(crate) fn answerable_task_id(raw: &[(Vec<u8>, Vec<u8>)]) -> Option<&str> {
286    fields::last(raw, "task_id").filter(|id| !id.is_empty() && id.len() <= ANSWERED_TASK_ID_MAX_LEN)
287}
288
289/// What a [`Handler`] returns for a task that succeeded: the fields of its output, which the
290/// worker adds to the result after the envelope's own.
291///
292/// ```
293/// use legit_streams::Reply;
294///
295/// let reply = Reply::new().field("result", "{\"ok\":true}").model_name("example-model");
296/// assert_eq!(reply.fields(), [("result".to_owned(), "{\"ok\":true}".to_owned())]);
297/// ```
298#[derive(Debug, Clone, Default, PartialEq, Eq)]
299pub struct Reply {
300    model_name: Option<String>,
301    fields: Vec<(String, String)>,
302}
303
304impl Reply {
305    /// A reply with no fields.
306    ///
307    /// ```
308    /// assert!(legit_streams::Reply::new().fields().is_empty());
309    /// ```
310    #[must_use]
311    pub fn new() -> Self {
312        Self::default()
313    }
314
315    /// Add an output field, such as `result` or `embedding`.
316    ///
317    /// ```
318    /// let reply = legit_streams::Reply::new().field("embedding_format", "base64_fp32");
319    /// assert_eq!(reply.fields().len(), 1);
320    /// ```
321    #[must_use]
322    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
323        self.fields.push((name.into(), value.into()));
324        self
325    }
326
327    /// Name the model that ran in the result's `model_name`, rather than echoing the task's: on a
328    /// success something ran, and its name may be fuller than the one the task asked for.
329    ///
330    /// ```
331    /// let reply = legit_streams::Reply::new().model_name("example-model");
332    /// # let _ = reply;
333    /// ```
334    #[must_use]
335    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
336        self.model_name = Some(model_name.into());
337        self
338    }
339
340    /// The output fields, in order.
341    ///
342    /// ```
343    /// assert!(legit_streams::Reply::default().fields().is_empty());
344    /// ```
345    #[must_use]
346    pub fn fields(&self) -> &[(String, String)] {
347        &self.fields
348    }
349}
350
351/// What a [`Handler`] returns for a task that failed: an error result, or, with
352/// [`Failure::abandon`], no result at all and the task left to another worker.
353///
354/// ```
355/// use legit_streams::Failure;
356///
357/// let failure = Failure::new("unsupported_model", "no model `x`").field("supported_models", "[\"a\"]");
358/// assert_eq!(failure.error_type(), Some("unsupported_model"));
359/// assert!(!failure.is_abandon());
360/// ```
361#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct Failure {
363    kind: FailureKind,
364    model_name: Option<String>,
365    fields: Vec<(String, String)>,
366}
367
368#[derive(Debug, Clone, PartialEq, Eq)]
369enum FailureKind {
370    Error { error_type: String, message: String },
371    Abandon { reason: String },
372}
373
374impl Failure {
375    /// An error result with this `error_type`, such as [`UNSUPPORTED_MODEL`], and message. Error
376    /// types are an open set in lowercase snake case: a type that isn't becomes an [`INTERNAL`]
377    /// error, as an unusable reply does.
378    ///
379    /// ```
380    /// let failure = legit_streams::Failure::new("decode_failed", "not an image");
381    /// assert_eq!(failure.message(), "not an image");
382    /// ```
383    #[must_use]
384    pub fn new(error_type: impl Into<String>, message: impl Into<String>) -> Self {
385        Self::of(FailureKind::Error {
386            error_type: error_type.into(),
387            message: message.into(),
388        })
389    }
390
391    /// No result, on the bulk lane: the worker leaves the task pending and releases it so another
392    /// worker claims it at once. For a handler that notices the worker stopping or its lease lost,
393    /// as [`Context::checkpoint`] does, or that can't run the task now; releasing is this crate's
394    /// feature, allowed at any time.
395    ///
396    /// Each release is followed by a claim, and each claim counts a delivery: a task released
397    /// three times reaches the default delivery limit, and its next claim is answered with
398    /// `max_deliveries_exceeded`. A task that shouldn't run at all is answered with an error, never
399    /// released.
400    ///
401    /// A [`FastWorker`](crate::FastWorker) never releases: it answers an abandoned task with an
402    /// [`INTERNAL`] error, so its caller falls back at once.
403    ///
404    /// ```
405    /// assert!(legit_streams::Failure::abandon("shutting down").is_abandon());
406    /// ```
407    #[must_use]
408    pub fn abandon(reason: impl Into<String>) -> Self {
409        Self::of(FailureKind::Abandon { reason: reason.into() })
410    }
411
412    const fn of(kind: FailureKind) -> Self {
413        Self {
414            kind,
415            model_name: None,
416            fields: Vec::new(),
417        }
418    }
419
420    /// Add a field to the error result, such as `supported_models`.
421    ///
422    /// ```
423    /// let failure = legit_streams::Failure::new("unsupported_model", "no").field("supported_models", "[]");
424    /// # let _ = failure;
425    /// ```
426    #[must_use]
427    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
428        self.fields.push((name.into(), value.into()));
429        self
430    }
431
432    /// Name the model that ran in the error result's `model_name`, rather than echoing the task's.
433    ///
434    /// Only for a failure of a stage after the model was chosen, when something ran. A task
435    /// refused before anything ran, such as one answered [`UNSUPPORTED_MODEL`] or [`INVALID_TASK`],
436    /// echoes the name it asked for: don't set another there.
437    ///
438    /// ```
439    /// let failure = legit_streams::Failure::new("decode_failed", "failed").model_name("example-model");
440    /// # let _ = failure;
441    /// ```
442    #[must_use]
443    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
444        self.model_name = Some(model_name.into());
445        self
446    }
447
448    /// Whether this abandons the task rather than answering it.
449    ///
450    /// ```
451    /// assert!(!legit_streams::Failure::new("decode_failed", "failed").is_abandon());
452    /// ```
453    #[must_use]
454    pub const fn is_abandon(&self) -> bool {
455        matches!(self.kind, FailureKind::Abandon { .. })
456    }
457
458    /// The error type, when the failure is an error with one.
459    ///
460    /// ```
461    /// assert_eq!(legit_streams::Failure::abandon("stop").error_type(), None);
462    /// ```
463    #[must_use]
464    pub fn error_type(&self) -> Option<&str> {
465        match &self.kind {
466            FailureKind::Error { error_type, .. } => Some(error_type),
467            FailureKind::Abandon { .. } => None,
468        }
469    }
470
471    /// The error message, or the reason for abandoning.
472    ///
473    /// ```
474    /// assert_eq!(legit_streams::Failure::abandon("stop").message(), "stop");
475    /// ```
476    #[must_use]
477    pub fn message(&self) -> &str {
478        match &self.kind {
479            FailureKind::Error { message, .. } => message,
480            FailureKind::Abandon { reason } => reason,
481        }
482    }
483}
484
485/// Runs a task. A worker calls it on a thread of its own for each task, so it must be `Sync`;
486/// a closure `Fn(&Task, &Context) -> Result<Reply, Failure>` is one.
487///
488/// A panic is caught and answered with an `internal` error result; the worker goes on.
489///
490/// ```
491/// use legit_streams::{Context, Failure, Handler, Reply, Task};
492///
493/// struct Upper;
494///
495/// impl Handler for Upper {
496///     fn handle(&self, task: &Task, _context: &Context) -> Result<Reply, Failure> {
497///         let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
498///         Ok(Reply::new().field("result", text.to_uppercase()))
499///     }
500/// }
501/// ```
502pub trait Handler: Send + Sync + 'static {
503    /// Run `task`.
504    ///
505    /// # Errors
506    ///
507    /// A [`Failure`], which the worker answers with an error result, or for
508    /// [`Failure::abandon`], releases to another worker on the bulk lane and answers with an
509    /// [`INTERNAL`] error on the fast lane.
510    ///
511    /// ```
512    /// use legit_streams::{Context, Failure, Reply, Task};
513    ///
514    /// fn handle(_task: &Task, _context: &Context) -> Result<Reply, Failure> {
515    ///     Err(Failure::new("unsupported_model", "no such model"))
516    /// }
517    /// # let _ = handle;
518    /// ```
519    fn handle(&self, task: &Task, context: &Context) -> std::result::Result<Reply, Failure>;
520}
521
522impl<F> Handler for F
523where
524    F: Fn(&Task, &Context) -> std::result::Result<Reply, Failure> + Send + Sync + 'static,
525{
526    fn handle(&self, task: &Task, context: &Context) -> std::result::Result<Reply, Failure> {
527        self(task, context)
528    }
529}
530
531/// What a handler can ask about the task it runs and the worker running it.
532///
533/// ```
534/// use legit_streams::{Context, Failure, Reply, Task};
535///
536/// fn handle(task: &Task, context: &Context) -> Result<Reply, Failure> {
537///     let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
538///     for chunk in text.split('\n') {
539///         context.checkpoint()?;
540///         let _ = chunk;
541///     }
542///     Ok(Reply::new())
543/// }
544/// # let _ = handle;
545/// ```
546pub struct Context {
547    entry_id: EntryId,
548    deliveries: u64,
549    reclaimed: bool,
550    flight: Arc<Flight>,
551    control: Arc<Control>,
552    clock: Clock,
553    /// When the worker took the task, on `clock`'s monotonic time.
554    started: Duration,
555}
556
557impl Context {
558    pub(crate) const fn new(
559        entry_id: EntryId,
560        deliveries: u64,
561        reclaimed: bool,
562        flight: Arc<Flight>,
563        control: Arc<Control>,
564        clock: Clock,
565        started: Duration,
566    ) -> Self {
567        Self {
568            entry_id,
569            deliveries,
570            reclaimed,
571            flight,
572            control,
573            clock,
574            started,
575        }
576    }
577
578    /// How long since the worker took the task, on the worker's clock: what the result's
579    /// `processing_ms` reports if the handler returns now, to the nanosecond rather than the
580    /// millisecond. It counts the worker's own steps before the handler ran, such as reading the
581    /// delivery count and renewing the lease, as `processing_ms` does.
582    ///
583    /// ```
584    /// # fn f(context: &legit_streams::Context) {
585    /// let so_far = context.elapsed();
586    /// # let _ = so_far;
587    /// # }
588    /// ```
589    #[must_use]
590    pub fn elapsed(&self) -> Duration {
591        self.clock.monotonic().saturating_sub(self.started)
592    }
593
594    /// The task's stream entry.
595    ///
596    /// ```
597    /// # fn f(context: &legit_streams::Context) {
598    /// println!("running entry {}", context.entry_id());
599    /// # }
600    /// ```
601    #[must_use]
602    pub const fn entry_id(&self) -> EntryId {
603        self.entry_id
604    }
605
606    /// How many times the task has been delivered, this time included, as the group's pending
607    /// list gave it when the worker took the task.
608    ///
609    /// It is 0 when the entry was no longer pending when its count was read, such as a task another
610    /// worker had already acknowledged, and 1 when the count couldn't be read. A
611    /// [`FastWorker`](crate::FastWorker) always gives 1.
612    ///
613    /// ```
614    /// # fn f(context: &legit_streams::Context) {
615    /// let retry = context.deliveries() > 1;
616    /// # let _ = retry;
617    /// # }
618    /// ```
619    #[must_use]
620    pub const fn deliveries(&self) -> u64 {
621        self.deliveries
622    }
623
624    /// Whether this worker claimed the task from another that stopped renewing it.
625    ///
626    /// ```
627    /// # fn f(context: &legit_streams::Context) {
628    /// let _ = context.is_reclaimed();
629    /// # }
630    /// ```
631    #[must_use]
632    pub const fn is_reclaimed(&self) -> bool {
633        self.reclaimed
634    }
635
636    /// Whether the worker has been asked to stop. A long task can abandon at a convenient point;
637    /// one that runs past the shutdown grace is released to another worker and its result
638    /// discarded.
639    ///
640    /// ```
641    /// # fn f(context: &legit_streams::Context) {
642    /// if context.is_stopping() { /* save progress */ }
643    /// # }
644    /// ```
645    #[must_use]
646    pub fn is_stopping(&self) -> bool {
647        self.control.stopping.load(Ordering::SeqCst)
648    }
649
650    /// Whether the worker lost the task's lease: another worker claimed it, or it was
651    /// acknowledged elsewhere. The worker discards the result of a task whose lease it lost.
652    ///
653    /// ```
654    /// # fn f(context: &legit_streams::Context) {
655    /// if context.is_lease_lost() { /* stop early */ }
656    /// # }
657    /// ```
658    #[must_use]
659    pub fn is_lease_lost(&self) -> bool {
660        self.flight.lost.load(Ordering::SeqCst)
661    }
662
663    /// `Err(Failure::abandon(..))` when the worker is stopping or has lost the lease, so a handler
664    /// can return early with `?` between stages. A [`Worker`] releases the task to another; a
665    /// [`FastWorker`](crate::FastWorker) answers it with an [`INTERNAL`] error.
666    ///
667    /// # Errors
668    ///
669    /// The abandoning [`Failure`], as above.
670    ///
671    /// ```
672    /// # fn f(context: &legit_streams::Context) -> Result<(), legit_streams::Failure> {
673    /// context.checkpoint()?;
674    /// # Ok(())
675    /// # }
676    /// ```
677    pub fn checkpoint(&self) -> std::result::Result<(), Failure> {
678        if self.is_stopping() {
679            return Err(Failure::abandon("the worker is stopping"));
680        }
681        if self.is_lease_lost() {
682            return Err(Failure::abandon("the lease on the task was lost"));
683        }
684        Ok(())
685    }
686}
687
688impl fmt::Debug for Context {
689    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
690        f.debug_struct("Context")
691            .field("entry_id", &self.entry_id)
692            .field("deliveries", &self.deliveries)
693            .field("reclaimed", &self.reclaimed)
694            .finish_non_exhaustive()
695    }
696}
697
698/// Asks a running [`Worker`] to stop. Cheap to clone.
699///
700/// ```
701/// use legit_streams::{MemoryStreams, Reply, Worker, WorkerConfig};
702///
703/// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
704/// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
705/// let stopper = worker.stopper();
706/// stopper.stop();
707/// assert!(stopper.is_stopped());
708/// # Ok::<(), legit_streams::Error>(())
709/// ```
710#[derive(Clone)]
711pub struct Stopper {
712    control: Arc<Control>,
713}
714
715impl Stopper {
716    pub(crate) const fn new(control: Arc<Control>) -> Self {
717        Self { control }
718    }
719
720    /// Ask the worker to stop: it takes no new task, waits up to
721    /// [`WorkerConfig::shutdown_grace`] for the tasks it runs, and releases the rest. A read in
722    /// progress finishes first, which takes up to [`WorkerConfig::read_block`].
723    ///
724    /// ```
725    /// # fn f(stopper: &legit_streams::Stopper) {
726    /// stopper.stop();
727    /// # }
728    /// ```
729    pub fn stop(&self) {
730        self.control.stopping.store(true, Ordering::SeqCst);
731        self.control.wake.raise();
732    }
733
734    /// Whether a stop was asked for.
735    ///
736    /// ```
737    /// # fn f(stopper: &legit_streams::Stopper) {
738    /// let _ = stopper.is_stopped();
739    /// # }
740    /// ```
741    #[must_use]
742    pub fn is_stopped(&self) -> bool {
743        self.control.stopping.load(Ordering::SeqCst)
744    }
745}
746
747impl fmt::Debug for Stopper {
748    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749        f.debug_struct("Stopper").field("stopped", &self.is_stopped()).finish()
750    }
751}
752
753/// What a worker did before it stopped.
754///
755/// ```
756/// use legit_streams::Report;
757///
758/// let report = Report::default();
759/// assert_eq!(report.results, 0);
760/// ```
761#[derive(Debug, Clone, Default, PartialEq, Eq)]
762#[non_exhaustive]
763pub struct Report {
764    /// How many results the worker wrote, errors included.
765    pub results: u64,
766    /// The entries the worker released to other workers rather than answering: tasks still
767    /// running when the shutdown grace ran out, tasks delivered after the stop, and tasks its
768    /// handler abandoned. Always empty for a [`FastWorker`](crate::FastWorker), which never
769    /// releases.
770    pub released: Vec<EntryId>,
771    /// Fast-lane entries deleted unanswered because their `deadline_ms` had passed when they were
772    /// read. Always 0 for a [`Worker`].
773    pub expired: u64,
774    /// Fast-lane entries deleted unanswered because their `reply_to` isn't the reply key of their
775    /// `task_id`. Always 0 for a [`Worker`].
776    pub invalid: u64,
777    /// Fast-lane tasks answered with an [`INTERNAL`] error because their handler abandoned them,
778    /// or because no thread could be started to run them; [`Report::results`] counts their
779    /// replies too. Always 0 for a [`Worker`].
780    pub abandoned: u64,
781}
782
783/// The worker side of the contract. It reads tasks from a stream with a consumer group, runs
784/// each with a [`Handler`] and writes the result to the reply stream, then acknowledges and
785/// deletes the task:
786///
787/// - It creates the group when missing.
788/// - Before each read it claims entries other consumers left idle past
789///   [`WorkerConfig::claim_idle`], and runs them first.
790/// - A task delivered more than [`WorkerConfig::max_deliveries`] times gets a
791///   `max_deliveries_exceeded` error result instead of another run.
792/// - While a task runs, a heartbeat renews its lease every [`WorkerConfig::lease_heartbeat`] with
793///   [`Streams::renew_lease`]: one atomic step that restarts the entry's idle time only if this
794///   worker still owns it. A lease found lost (the entry is another consumer's, or no longer
795///   pending, or the group is gone) is never taken back: the handler sees
796///   [`Context::is_lease_lost`], and its result is discarded. A renewal the server doesn't answer
797///   says nothing about the lease, and is tried again at the next heartbeat.
798/// - Before each try of writing a result, and of acknowledging the task, retries included, the
799///   worker checks the lease: the heartbeat's finding, then a renewal. Once it's lost, the worker
800///   writes nothing more and acknowledges nothing.
801/// - An entry that isn't a valid task, a handler error or panic, and a result over the limits
802///   each become an error result; none stops the loop.
803/// - A result goes to the stream its task's `reply_to` names; when that isn't a valid reply
804///   stream, the task still runs and its result goes to [`WorkerConfig::result_stream`].
805/// - The result goes to the stream before the task is acknowledged, so a crash between the two
806///   repeats a result rather than losing one.
807/// - On [`Stopper::stop`] it takes no new task, waits for running tasks up to
808///   [`WorkerConfig::shutdown_grace`], then releases the rest with [`Streams::release_lease`],
809///   setting their idle time to `claim_idle` so another worker claims them at once rather than
810///   after the idle threshold, and removes its consumer when it owns nothing.
811///
812/// Results are at least once. A worker that lost its lease between two renewals finds out at the
813/// next one, or right before its write; but a worker that stalls for a whole `claim_idle` between
814/// that last renewal and its write, or crashes between the write and the acknowledgement, writes a
815/// result another run writes too. A reader of results must treat a second result for a `task_id`
816/// as a repeat.
817///
818/// ```
819/// use std::time::Duration;
820/// use legit_streams::{Clock, Failure, MemoryStreams, Reply, Streams, Task, Worker, WorkerConfig};
821///
822/// let clock = Clock::manual(1_000);
823/// let streams = MemoryStreams::with_clock(clock.clone());
824/// let task = Task::builder("app", "post", "42").field("text_data", "hello").build()?;
825/// let fields: Vec<(&[u8], &[u8])> = task.fields().iter().map(|(k, v)| (k.as_bytes(), v.as_bytes())).collect();
826/// streams.xadd("hash_tasks", &fields)?;
827///
828/// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
829/// let worker = Worker::new(config, streams.clone(), |task: &Task, _: &_| {
830///     let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
831///     Ok(Reply::new().field("result", text.to_uppercase()))
832/// })?
833/// .clock(clock.clone());
834/// let running = worker.spawn()?;
835///
836/// while streams.xlen("hash_results")? == 0 {
837///     std::thread::sleep(Duration::from_millis(1));
838/// }
839/// running.stop();
840/// clock.advance(Duration::from_secs(5));
841/// let report = running.join()?;
842///
843/// assert_eq!(report.results, 1);
844/// assert_eq!(streams.entries("hash_results")[0].field("result"), Some(&b"HELLO"[..]));
845/// assert_eq!(streams.xlen("hash_tasks")?, 0);
846/// # Ok::<(), legit_streams::Error>(())
847/// ```
848pub struct Worker {
849    config: Arc<WorkerConfig>,
850    streams: Arc<dyn Streams>,
851    handler: Arc<dyn Handler>,
852    clock: Clock,
853    control: Arc<Control>,
854}
855
856pub(crate) struct Control {
857    pub(crate) stopping: AtomicBool,
858    pub(crate) wake: Signal,
859}
860
861impl Control {
862    pub(crate) fn new(clock: &Clock) -> Arc<Self> {
863        Arc::new(Self {
864            stopping: AtomicBool::new(false),
865            wake: Signal::new(clock),
866        })
867    }
868}
869
870impl Worker {
871    /// A worker with these settings, on the system clock.
872    ///
873    /// # Errors
874    ///
875    /// [`Error::InvalidConfig`] for settings that can't work, such as an empty stream name, a task
876    /// stream beginning with `results:` or `dead:`, a concurrency of 0, or a lease heartbeat no
877    /// shorter than the claim idle time.
878    ///
879    /// ```
880    /// use legit_streams::{Error, MemoryStreams, Reply, Worker, WorkerConfig};
881    ///
882    /// let config = WorkerConfig { concurrency: 0, ..WorkerConfig::new("hash_tasks", "hash_workers", "w", "hash_results") };
883    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()));
884    /// assert!(matches!(worker, Err(Error::InvalidConfig(_))));
885    ///
886    /// let config = WorkerConfig::new("results:app:hash", "hash_workers", "w", "hash_results");
887    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()));
888    /// assert!(matches!(worker, Err(Error::InvalidConfig(_))));
889    /// ```
890    pub fn new(config: WorkerConfig, streams: impl Streams + 'static, handler: impl Handler) -> Result<Self> {
891        config.validate()?;
892        let clock = Clock::system();
893        Ok(Self {
894            config: Arc::new(config),
895            streams: Arc::new(streams),
896            handler: Arc::new(handler),
897            control: Control::new(&clock),
898            clock,
899        })
900    }
901
902    /// Run on `clock` rather than the system clock, such as a manual clock in tests. Take
903    /// [`Worker::stopper`] after this.
904    ///
905    /// ```
906    /// use legit_streams::{Clock, MemoryStreams, Reply, Worker, WorkerConfig};
907    ///
908    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "w", "hash_results");
909    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?.clock(Clock::manual(0));
910    /// # Ok::<(), legit_streams::Error>(())
911    /// ```
912    #[must_use]
913    pub fn clock(mut self, clock: Clock) -> Self {
914        self.control = Control::new(&clock);
915        self.clock = clock;
916        self
917    }
918
919    /// The handle that stops this worker.
920    ///
921    /// ```
922    /// use legit_streams::{MemoryStreams, Reply, Worker, WorkerConfig};
923    ///
924    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "w", "hash_results");
925    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
926    /// assert!(!worker.stopper().is_stopped());
927    /// # Ok::<(), legit_streams::Error>(())
928    /// ```
929    #[must_use]
930    pub fn stopper(&self) -> Stopper {
931        Stopper::new(Arc::clone(&self.control))
932    }
933
934    /// The worker's settings.
935    ///
936    /// ```
937    /// use legit_streams::{MemoryStreams, Reply, Worker, WorkerConfig};
938    ///
939    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "w", "hash_results");
940    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
941    /// assert_eq!(worker.config().consumer, "w");
942    /// # Ok::<(), legit_streams::Error>(())
943    /// ```
944    #[must_use]
945    pub fn config(&self) -> &WorkerConfig {
946        &self.config
947    }
948
949    /// Run the worker on a thread of its own.
950    ///
951    /// # Errors
952    ///
953    /// [`Error::Thread`] when the thread can't be started.
954    ///
955    /// ```no_run
956    /// use legit_streams::{RedisStreams, Reply, Worker, WorkerConfig};
957    ///
958    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
959    /// let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
960    /// let running = Worker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?.spawn()?;
961    /// running.stop();
962    /// running.join()?;
963    /// # Ok::<(), legit_streams::Error>(())
964    /// ```
965    pub fn spawn(self) -> Result<Running> {
966        let stopper = self.stopper();
967        let thread = thread::Builder::new()
968            .name("legit-streams-worker".to_owned())
969            .spawn(move || self.run())
970            .map_err(|error| Error::Thread(error.to_string()))?;
971        Ok(Running::new(stopper, thread))
972    }
973
974    /// Run the worker on this thread until [`Stopper::stop`].
975    ///
976    /// # Errors
977    ///
978    /// [`Error::Redis`] when the group can't be created at the start, and [`Error::Thread`] when
979    /// the lease heartbeat's thread can't be started. Once running, a failed command is logged
980    /// and retried, never returned.
981    ///
982    /// ```no_run
983    /// use legit_streams::{RedisStreams, Reply, Worker, WorkerConfig};
984    ///
985    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
986    /// let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
987    /// let worker = Worker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?;
988    /// let report = worker.run()?;
989    /// println!("{} results", report.results);
990    /// # Ok::<(), legit_streams::Error>(())
991    /// ```
992    pub fn run(&self) -> Result<Report> {
993        let party = self.clock.party();
994        party.bind();
995        let config = &self.config;
996        self.streams.xgroup_create(&config.stream, &config.group)?;
997        let run = Arc::new(Run {
998            config: Arc::clone(config),
999            streams: Arc::clone(&self.streams),
1000            handler: Arc::clone(&self.handler),
1001            clock: self.clock.clone(),
1002            control: Arc::clone(&self.control),
1003            flights: Mutex::new(HashMap::new()),
1004            results: AtomicU64::new(0),
1005            released: Mutex::new(Vec::new()),
1006            lease_stop: AtomicBool::new(false),
1007            lease_wake: Signal::new(&self.clock),
1008        });
1009        let lease_party = self.clock.party();
1010        let lease_run = Arc::clone(&run);
1011        let lease = thread::Builder::new()
1012            .name("legit-streams-lease".to_owned())
1013            .spawn(move || {
1014                lease_party.bind();
1015                lease_run.lease_loop();
1016            })
1017            .map_err(|error| Error::Thread(error.to_string()))?;
1018        tracing::info!(stream = %config.stream, group = %config.group, consumer = %config.consumer, "Worker started");
1019        run.read_loop();
1020        run.shut_down();
1021        run.lease_stop.store(true, Ordering::SeqCst);
1022        run.lease_wake.raise();
1023        if lease.join().is_err() {
1024            tracing::error!("The lease heartbeat thread panicked");
1025        }
1026        run.remove_consumer();
1027        let report = Report {
1028            results: run.results.load(Ordering::SeqCst),
1029            released: run.lock_released().clone(),
1030            ..Report::default()
1031        };
1032        tracing::info!(
1033            results = report.results,
1034            released = report.released.len(),
1035            "Worker stopped"
1036        );
1037        Ok(report)
1038    }
1039}
1040
1041impl fmt::Debug for Worker {
1042    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043        f.debug_struct("Worker")
1044            .field("config", &self.config)
1045            .field("streams", &self.streams)
1046            .field("clock", &self.clock)
1047            .finish_non_exhaustive()
1048    }
1049}
1050
1051/// A worker running on a thread of its own, from [`Worker::spawn`].
1052///
1053/// ```no_run
1054/// # fn f(running: legit_streams::Running) -> legit_streams::Result<()> {
1055/// running.stop();
1056/// let report = running.join()?;
1057/// # let _ = report;
1058/// # Ok(())
1059/// # }
1060/// ```
1061#[derive(Debug)]
1062pub struct Running {
1063    stopper: Stopper,
1064    thread: JoinHandle<Result<Report>>,
1065}
1066
1067impl Running {
1068    pub(crate) const fn new(stopper: Stopper, thread: JoinHandle<Result<Report>>) -> Self {
1069        Self { stopper, thread }
1070    }
1071
1072    /// Ask the worker to stop; see [`Stopper::stop`].
1073    ///
1074    /// ```no_run
1075    /// # fn f(running: &legit_streams::Running) {
1076    /// running.stop();
1077    /// # }
1078    /// ```
1079    pub fn stop(&self) {
1080        self.stopper.stop();
1081    }
1082
1083    /// The handle that stops the worker.
1084    ///
1085    /// ```no_run
1086    /// # fn f(running: &legit_streams::Running) {
1087    /// let stopper = running.stopper();
1088    /// # let _ = stopper;
1089    /// # }
1090    /// ```
1091    #[must_use]
1092    pub fn stopper(&self) -> Stopper {
1093        self.stopper.clone()
1094    }
1095
1096    /// Whether the worker has stopped, so [`Running::join`] won't wait.
1097    ///
1098    /// ```no_run
1099    /// # fn f(running: &legit_streams::Running) {
1100    /// if running.is_finished() { /* join */ }
1101    /// # }
1102    /// ```
1103    #[must_use]
1104    pub fn is_finished(&self) -> bool {
1105        self.thread.is_finished()
1106    }
1107
1108    /// Wait for the worker to stop.
1109    ///
1110    /// # Errors
1111    ///
1112    /// The errors of [`Worker::run`].
1113    ///
1114    /// # Panics
1115    ///
1116    /// When the worker's thread panicked, with its panic.
1117    ///
1118    /// ```no_run
1119    /// # fn f(running: legit_streams::Running) -> legit_streams::Result<()> {
1120    /// let report = running.join()?;
1121    /// # let _ = report;
1122    /// # Ok(())
1123    /// # }
1124    /// ```
1125    pub fn join(self) -> Result<Report> {
1126        self.thread.join().unwrap_or_else(|panic| panic::resume_unwind(panic))
1127    }
1128}
1129
1130/// A task taken from the stream: running, being answered, or released.
1131#[derive(Default)]
1132pub(crate) struct Flight {
1133    pub(crate) state: AtomicU8,
1134    leased: AtomicBool,
1135    lost: AtomicBool,
1136    /// Set once the worker starts to acknowledge the entry: from then on, an entry no longer
1137    /// pending may be one this worker has acknowledged.
1138    acking: AtomicBool,
1139    /// Held across a heartbeat and across a release, so a renewal can't land after a release
1140    /// and undo it.
1141    lease: Mutex<()>,
1142}
1143
1144pub(crate) const ACTIVE: u8 = 0;
1145pub(crate) const FINISHING: u8 = 1;
1146pub(crate) const RELEASED: u8 = 2;
1147
1148impl Flight {
1149    pub(crate) fn moves(&self, from: u8, to: u8) -> bool {
1150        self.state
1151            .compare_exchange(from, to, Ordering::SeqCst, Ordering::SeqCst)
1152            .is_ok()
1153    }
1154
1155    fn lock_lease(&self) -> MutexGuard<'_, ()> {
1156        self.lease.lock().unwrap_or_else(PoisonError::into_inner)
1157    }
1158}
1159
1160/// One run of a worker: what the read loop, the lease heartbeat and the task threads share.
1161struct Run {
1162    config: Arc<WorkerConfig>,
1163    streams: Arc<dyn Streams>,
1164    handler: Arc<dyn Handler>,
1165    clock: Clock,
1166    control: Arc<Control>,
1167    flights: Mutex<HashMap<EntryId, Arc<Flight>>>,
1168    results: AtomicU64,
1169    released: Mutex<Vec<EntryId>>,
1170    lease_stop: AtomicBool,
1171    lease_wake: Signal,
1172}
1173
1174impl Run {
1175    fn stopping(&self) -> bool {
1176        self.control.stopping.load(Ordering::SeqCst)
1177    }
1178
1179    fn lock_flights(&self) -> MutexGuard<'_, HashMap<EntryId, Arc<Flight>>> {
1180        self.flights.lock().unwrap_or_else(PoisonError::into_inner)
1181    }
1182
1183    fn lock_released(&self) -> MutexGuard<'_, Vec<EntryId>> {
1184        self.released.lock().unwrap_or_else(PoisonError::into_inner)
1185    }
1186
1187    fn read_loop(self: &Arc<Self>) {
1188        let config = &self.config;
1189        let mut cursor = EntryId::ZERO;
1190        while !self.stopping() {
1191            let seen = self.control.wake.seen();
1192            let free = config.concurrency.saturating_sub(self.lock_flights().len());
1193            if free == 0 {
1194                self.clock.wait(Some((&self.control.wake, seen)), None);
1195                continue;
1196            }
1197            match self.streams.xautoclaim(
1198                &config.stream,
1199                &config.group,
1200                &config.consumer,
1201                config.claim_idle,
1202                cursor,
1203                free,
1204            ) {
1205                Ok(claim) => {
1206                    cursor = claim.next;
1207                    if !claim.deleted.is_empty()
1208                        && let Err(error) = self.streams.xack_xdel(&config.stream, &config.group, &claim.deleted)
1209                    {
1210                        tracing::warn!(%error, "Couldn't acknowledge claimed entries that were deleted");
1211                    }
1212                    if !claim.claimed.is_empty() {
1213                        for entry in claim.claimed {
1214                            // Our own entry, idle after missed heartbeats: its handler still runs,
1215                            // and the claim renewed its lease...
1216                            if self.lock_flights().contains_key(&entry.id) {
1217                                tracing::warn!(entry = %entry.id, "Claimed back an entry this worker still runs");
1218                                continue;
1219                            }
1220                            tracing::info!(entry = %entry.id, "Claimed an entry another consumer left idle");
1221                            self.dispatch(entry, true);
1222                        }
1223                        continue;
1224                    }
1225                }
1226                Err(error) => {
1227                    cursor = EntryId::ZERO;
1228                    tracing::warn!(%error, "Couldn't claim idle entries");
1229                }
1230            }
1231            if self.stopping() {
1232                break;
1233            }
1234            match self.streams.xreadgroup(
1235                &config.stream,
1236                &config.group,
1237                &config.consumer,
1238                free,
1239                Some(config.read_block),
1240            ) {
1241                Ok(entries) => {
1242                    for entry in entries {
1243                        if self.stopping() {
1244                            self.release(entry.id, "delivered after the stop");
1245                        } else {
1246                            self.dispatch(entry, false);
1247                        }
1248                    }
1249                }
1250                Err(error) => {
1251                    tracing::error!(%error, "Couldn't read tasks");
1252                    if matches!(error, Error::NoGroup { .. })
1253                        && let Err(error) = self.streams.xgroup_create(&config.stream, &config.group)
1254                    {
1255                        tracing::error!(%error, "Couldn't create the consumer group again");
1256                    }
1257                    let deadline = self.clock.monotonic().saturating_add(READ_RETRY);
1258                    self.clock.wait(Some((&self.control.wake, seen)), Some(deadline));
1259                }
1260            }
1261        }
1262    }
1263
1264    fn dispatch(self: &Arc<Self>, entry: Entry, reclaimed: bool) {
1265        let id = entry.id;
1266        // Leased from now: the heartbeat covers the entry before its thread first runs...
1267        let flight = Arc::new(Flight {
1268            leased: AtomicBool::new(true),
1269            ..Flight::default()
1270        });
1271        self.lock_flights().insert(id, Arc::clone(&flight));
1272        let run = Arc::clone(self);
1273        let running = Arc::clone(&flight);
1274        let spawned = thread::Builder::new()
1275            .name("legit-streams-task".to_owned())
1276            .spawn(move || {
1277                run.process(&entry, reclaimed, &running);
1278                run.remove_flight(entry.id, &running);
1279                run.control.wake.raise();
1280            });
1281        if let Err(error) = spawned {
1282            tracing::error!(entry = %id, %error, "Couldn't start a thread for a task");
1283            self.remove_flight(id, &flight);
1284            self.release(id, "no thread to run it on");
1285        }
1286    }
1287
1288    /// Forget a flight, unless the entry's id has since been given to another one.
1289    fn remove_flight(&self, id: EntryId, flight: &Arc<Flight>) {
1290        let mut flights = self.lock_flights();
1291        if flights.get(&id).is_some_and(|current| Arc::ptr_eq(current, flight)) {
1292            flights.remove(&id);
1293        }
1294    }
1295
1296    fn process(&self, entry: &Entry, reclaimed: bool, flight: &Arc<Flight>) {
1297        let config = &self.config;
1298        let started = self.clock.monotonic();
1299        let deliveries = match self.streams.xpending_entry(&config.stream, &config.group, entry.id) {
1300            Ok(Some(pending)) => pending.deliveries,
1301            Ok(None) => 0,
1302            Err(error) => {
1303                tracing::warn!(entry = %entry.id, %error, "Couldn't read the delivery count; taking it as the first");
1304                1
1305            }
1306        };
1307        if deliveries > config.max_deliveries {
1308            let message = format!(
1309                "delivered {deliveries} times (max {}); earlier attempts died mid-task",
1310                config.max_deliveries
1311            );
1312            self.refuse(entry, flight, message, MAX_DELIVERIES_EXCEEDED, started);
1313            return;
1314        }
1315        let task = match Task::from_raw(&entry.fields, &config.limits) {
1316            Ok(task) => task,
1317            Err(error) => {
1318                tracing::warn!(entry = %entry.id, %error, "The entry isn't a valid task");
1319                let error_type = if matches!(error, Error::UnsupportedVersion(_)) {
1320                    UNSUPPORTED_VERSION
1321                } else {
1322                    INVALID_TASK
1323                };
1324                self.refuse(entry, flight, error.to_string(), error_type, started);
1325                return;
1326            }
1327        };
1328        if flight.state.load(Ordering::SeqCst) == RELEASED {
1329            return;
1330        }
1331        self.beat(entry.id, flight);
1332        let context = Context::new(
1333            entry.id,
1334            deliveries,
1335            reclaimed,
1336            Arc::clone(flight),
1337            Arc::clone(&self.control),
1338            self.clock.clone(),
1339            started,
1340        );
1341        tracing::debug!(task_id = task.task_id(), entry = %entry.id, deliveries, "Running a task");
1342        let outcome = panic::catch_unwind(AssertUnwindSafe(|| self.handler.handle(&task, &context)));
1343        if let Ok(Err(failure)) = &outcome
1344            && failure.is_abandon()
1345        {
1346            tracing::info!(
1347                task_id = task.task_id(),
1348                reason = failure.message(),
1349                "The handler abandoned a task"
1350            );
1351            self.release_flight(entry.id, flight, "abandoned by the handler");
1352            return;
1353        }
1354        if flight.lost.load(Ordering::SeqCst) {
1355            tracing::warn!(task_id = task.task_id(), entry = %entry.id, "The task finished after its lease was lost; its result is discarded");
1356            return;
1357        }
1358        let Some(result) = answer(&task, outcome) else {
1359            return;
1360        };
1361        self.finish(
1362            entry,
1363            flight,
1364            result,
1365            Origin::Handler,
1366            task.reply_to().map(str::to_owned),
1367            started,
1368        );
1369    }
1370
1371    /// Answer an entry that isn't run with an error of this type, carrying its `task_id` exactly as
1372    /// sent and routed as any result is; or, when it has no `task_id` to answer with (none, an
1373    /// empty one, or one that isn't UTF-8 of at most 256 bytes), remove it unanswered.
1374    fn refuse(&self, entry: &Entry, flight: &Flight, message: String, error_type: &str, started: Duration) {
1375        let Some(task_id) = answerable_task_id(&entry.fields) else {
1376            tracing::warn!(entry = %entry.id, error_type, "The entry has no `task_id` to answer with; it's removed without a result");
1377            self.remove(entry, flight);
1378            return;
1379        };
1380        let result =
1381            ResultBuilder::for_raw(&entry.fields, Some(task_id), Status::Error, message).error_type(error_type);
1382        self.finish(
1383            entry,
1384            flight,
1385            result,
1386            Origin::Refusal,
1387            fields::last(&entry.fields, "reply_to").map(str::to_owned),
1388            started,
1389        );
1390    }
1391
1392    /// Acknowledge and delete an entry without a result, unless the lease on it is lost.
1393    fn remove(&self, entry: &Entry, flight: &Flight) {
1394        if !flight.moves(ACTIVE, FINISHING) {
1395            return;
1396        }
1397        self.acknowledge(entry.id, flight, "remove an entry that isn't a task");
1398    }
1399
1400    /// Write the result, then acknowledge and delete the task.
1401    ///
1402    /// Each try of the write, and of the acknowledgement, first checks the lease: a flag the
1403    /// heartbeat set, then a renewal. A lease found lost at any of them, before the first write
1404    /// or while a failed write or acknowledgement is retried, means another worker has the task:
1405    /// this one stops, writes nothing more, and leaves the entry to it. A renewal that passes also
1406    /// restarts the idle time, so no other worker can claim the entry for a whole `claim_idle`
1407    /// before the step it guards.
1408    fn finish(
1409        &self,
1410        entry: &Entry,
1411        flight: &Flight,
1412        result: ResultBuilder,
1413        origin: Origin,
1414        reply_to: Option<String>,
1415        started: Duration,
1416    ) {
1417        if !flight.moves(ACTIVE, FINISHING) {
1418            return;
1419        }
1420        let config = &self.config;
1421        let elapsed = self.clock.monotonic().saturating_sub(started);
1422        let result = result
1423            .worker_id(&config.consumer)
1424            .processing_ms(u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX));
1425        let fields = result_fields(&config.limits, result, origin);
1426        let stream = match reply_to.filter(|reply_to| config.route_results_per_app && !reply_to.is_empty()) {
1427            Some(reply_to) if is_valid_reply_to(&reply_to) => reply_to,
1428            Some(_) => {
1429                tracing::warn!(entry = %entry.id, stream = %config.result_stream, "The task's `reply_to` isn't a valid reply stream; its result goes to the default result stream");
1430                config.result_stream.clone()
1431            }
1432            None => config.result_stream.clone(),
1433        };
1434        let pairs = fields::as_bytes(&fields);
1435        let written = self.attempt("write the result", || {
1436            if let Some(lost) = self.check(entry.id, flight) {
1437                tracing::warn!(entry = %entry.id, reason = %lost, "The lease was lost before the result was written; the result is discarded");
1438                return Ok(false);
1439            }
1440            self.streams.xadd(&stream, &pairs).map(|_| true)
1441        });
1442        if !written {
1443            return;
1444        }
1445        self.results.fetch_add(1, Ordering::SeqCst);
1446        self.acknowledge(entry.id, flight, "acknowledge the task");
1447    }
1448
1449    /// Acknowledge and delete an entry, with the lease checked before each try.
1450    ///
1451    /// A lease known lost, from the heartbeat or an earlier check, stops every try, and so does a
1452    /// renewal that finds another consumer owning the entry. Once a try has been sent, part of it
1453    /// may have landed (`XACK` and `XDEL` are two commands), so a renewal that finds the entry no
1454    /// longer pending doesn't mark the lease lost: that's this worker's own acknowledgement, and
1455    /// only its deletion is tried again, for as many tries as are left.
1456    fn acknowledge(&self, id: EntryId, flight: &Flight, what: &str) {
1457        let config = &self.config;
1458        let ids = [id];
1459        let mut sent = false;
1460        self.attempt(what, || {
1461            let lost = if sent {
1462                // A loss already known stays known, whatever this renewal answers; a renewal
1463                // that finds the entry no longer pending marks nothing, since that may be this
1464                // worker's own acknowledgement...
1465                let _lease = flight.lock_lease();
1466                if flight.lost.load(Ordering::SeqCst) {
1467                    Some(Lost::Earlier)
1468                } else {
1469                    let lost = self.renew(id);
1470                    if lost.is_some_and(|lost| !matches!(lost, Lost::Lease(LostLease::NotPending))) {
1471                        flight.lost.store(true, Ordering::SeqCst);
1472                    }
1473                    lost
1474                }
1475            } else {
1476                self.check(id, flight)
1477            };
1478            match lost {
1479                Some(Lost::Lease(LostLease::NotPending)) if sent => {
1480                    return self.streams.xdel(&config.stream, &ids).map(|_| true);
1481                }
1482                Some(lost) => {
1483                    tracing::warn!(entry = %id, reason = %lost, "The lease was lost before the entry was acknowledged; it's left to its owner");
1484                    return Ok(false);
1485                }
1486                None => {}
1487            }
1488            flight.acking.store(true, Ordering::SeqCst);
1489            sent = true;
1490            self.streams.xack_xdel(&config.stream, &config.group, &ids).map(|()| true)
1491        });
1492    }
1493
1494    /// The lease right before a step of finishing: `Some` when it's known lost, from the
1495    /// heartbeat or from a renewal made now. A renewal the server doesn't answer says nothing,
1496    /// and the step goes ahead.
1497    fn check(&self, id: EntryId, flight: &Flight) -> Option<Lost> {
1498        let _lease = flight.lock_lease();
1499        if flight.lost.load(Ordering::SeqCst) {
1500            return Some(Lost::Earlier);
1501        }
1502        let lost = self.renew(id);
1503        if lost.is_some() {
1504            flight.lost.store(true, Ordering::SeqCst);
1505        }
1506        lost
1507    }
1508
1509    /// Run `step` up to `flush_attempts` times with a growing wait, returning whether it worked.
1510    /// A step answers `Ok(true)` when done, `Ok(false)` to stop without retrying, such as on a
1511    /// lost lease, and an error to be tried again.
1512    fn attempt(&self, what: &str, mut step: impl FnMut() -> Result<bool>) -> bool {
1513        let attempts = self.config.flush_attempts;
1514        for attempt in 1..=attempts {
1515            match step() {
1516                Ok(done) => return done,
1517                Err(error) if attempt == attempts => {
1518                    tracing::error!(%error, attempt, "Couldn't {what}; the task stays pending for another worker");
1519                }
1520                Err(error) => {
1521                    tracing::warn!(%error, attempt, "Couldn't {what}; trying again");
1522                    self.clock.sleep(self.config.flush_backoff.saturating_mul(attempt));
1523                }
1524            }
1525        }
1526        false
1527    }
1528
1529    fn lease_loop(&self) {
1530        loop {
1531            let seen = self.lease_wake.seen();
1532            if self.lease_stop.load(Ordering::SeqCst) {
1533                return;
1534            }
1535            let leased: Vec<(EntryId, Arc<Flight>)> = self
1536                .lock_flights()
1537                .iter()
1538                .filter(|(_, flight)| flight.leased.load(Ordering::SeqCst))
1539                .map(|(id, flight)| (*id, Arc::clone(flight)))
1540                .collect();
1541            for (id, flight) in &leased {
1542                self.beat(*id, flight);
1543            }
1544            let deadline = self.clock.monotonic().saturating_add(self.config.lease_heartbeat);
1545            self.clock.wait(Some((&self.lease_wake, seen)), Some(deadline));
1546        }
1547    }
1548
1549    /// Renew the lease on an entry while its task runs, and mark the lease lost when it is.
1550    fn beat(&self, id: EntryId, flight: &Flight) {
1551        let _lease = flight.lock_lease();
1552        // The lease holds until the task is acknowledged, so no one claims it while its result
1553        // is being written...
1554        let state = flight.state.load(Ordering::SeqCst);
1555        if flight.lost.load(Ordering::SeqCst) || state == RELEASED {
1556            return;
1557        }
1558        match self.renew(id) {
1559            // ...and once this worker has started to acknowledge it, the entry may be gone for
1560            // that reason.
1561            Some(Lost::Lease(LostLease::NotPending)) if state == FINISHING && flight.acking.load(Ordering::SeqCst) => {}
1562            Some(lost) => {
1563                flight.lost.store(true, Ordering::SeqCst);
1564                tracing::error!(entry = %id, reason = %lost, "Lost the lease on a task");
1565            }
1566            None => {}
1567        }
1568    }
1569
1570    /// Renew the lease on an entry: `None` when it was renewed, or when the server couldn't say,
1571    /// which leaves the lease as it was until the next try; the reason when it's lost.
1572    ///
1573    /// A renewal is [`Streams::renew_lease`], one atomic step on the server. Reading the consumer's
1574    /// own history with `XREADGROUP … 0` would reset the idle time too, but it counts a delivery on
1575    /// every read, so a slow task would use up its delivery limit; it isn't a renewal.
1576    fn renew(&self, id: EntryId) -> Option<Lost> {
1577        let config = &self.config;
1578        match self
1579            .streams
1580            .renew_lease(&config.stream, &config.group, &config.consumer, id)
1581        {
1582            Ok(Renewal::Renewed) => None,
1583            Ok(Renewal::Lost(lost)) => Some(Lost::Lease(lost)),
1584            Err(Error::NoGroup { .. }) => Some(Lost::NoGroup),
1585            Err(error) => {
1586                tracing::warn!(entry = %id, %error, "Couldn't renew a lease; trying again at the next heartbeat");
1587                None
1588            }
1589        }
1590    }
1591
1592    /// Release a task that hasn't been answered, unless it's being answered already.
1593    fn release_flight(&self, id: EntryId, flight: &Flight, why: &str) {
1594        let _lease = flight.lock_lease();
1595        if flight.moves(ACTIVE, RELEASED) {
1596            self.release(id, why);
1597        }
1598    }
1599
1600    /// Hand an entry this worker owns to the next worker that claims idle entries. An entry
1601    /// another worker has claimed meanwhile is left with it: the check and the release are one
1602    /// step, [`Streams::release_lease`].
1603    fn release(&self, id: EntryId, why: &str) {
1604        let config = &self.config;
1605        match self
1606            .streams
1607            .release_lease(&config.stream, &config.group, &config.consumer, id, config.claim_idle)
1608        {
1609            Ok(true) => tracing::info!(entry = %id, why, "Released an entry to other workers"),
1610            Ok(false) => tracing::info!(entry = %id, why, "Didn't release an entry: it's no longer this worker's"),
1611            Err(error) => {
1612                tracing::warn!(entry = %id, why, %error, "Couldn't release an entry; it's claimable once idle");
1613            }
1614        }
1615        self.lock_released().push(id);
1616    }
1617
1618    /// Wait for running tasks up to the grace, release what's still running, and wait for results
1619    /// being written.
1620    fn shut_down(&self) {
1621        let deadline = self.clock.monotonic().saturating_add(self.config.shutdown_grace);
1622        loop {
1623            let seen = self.control.wake.seen();
1624            if self.lock_flights().is_empty() || self.clock.monotonic() >= deadline {
1625                break;
1626            }
1627            self.clock.wait(Some((&self.control.wake, seen)), Some(deadline));
1628        }
1629        let running: Vec<(EntryId, Arc<Flight>)> = self
1630            .lock_flights()
1631            .iter()
1632            .map(|(id, flight)| (*id, Arc::clone(flight)))
1633            .collect();
1634        for (id, flight) in running {
1635            self.release_flight(id, &flight, "still running when the shutdown grace ran out");
1636        }
1637        loop {
1638            let seen = self.control.wake.seen();
1639            let finishing = self
1640                .lock_flights()
1641                .values()
1642                .any(|flight| flight.state.load(Ordering::SeqCst) == FINISHING);
1643            if !finishing {
1644                return;
1645            }
1646            self.clock.wait(Some((&self.control.wake, seen)), None);
1647        }
1648    }
1649
1650    /// Remove this worker's consumer from the group, unless it still owns entries.
1651    fn remove_consumer(&self) {
1652        let config = &self.config;
1653        match self
1654            .streams
1655            .xpending_consumer(&config.stream, &config.group, &config.consumer, 1)
1656        {
1657            Ok(owned) if owned.is_empty() => {
1658                if let Err(error) = self
1659                    .streams
1660                    .xgroup_delconsumer(&config.stream, &config.group, &config.consumer)
1661                {
1662                    tracing::debug!(%error, "Couldn't remove the consumer");
1663                }
1664            }
1665            Ok(_) => {}
1666            Err(error) => tracing::debug!(%error, "Couldn't check what the consumer owns"),
1667        }
1668    }
1669}
1670
1671/// Why a worker lost a lease.
1672#[derive(Debug, Clone, Copy)]
1673enum Lost {
1674    /// The entry isn't this consumer's any more.
1675    Lease(LostLease),
1676    /// The consumer group is gone, and its pending list with it.
1677    NoGroup,
1678    /// The heartbeat, or an earlier check, found the lease lost.
1679    Earlier,
1680}
1681
1682impl fmt::Display for Lost {
1683    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1684        match self {
1685            Self::Lease(lost) => lost.fmt(f),
1686            Self::NoGroup => f.write_str("the consumer group is gone"),
1687            Self::Earlier => f.write_str("the lease was found lost earlier"),
1688        }
1689    }
1690}
1691
1692/// What a handler returned, or how it panicked.
1693pub(crate) type Outcome = std::thread::Result<std::result::Result<Reply, Failure>>;
1694
1695/// The result of a task from its handler's outcome; `None` when the handler abandoned it.
1696pub(crate) fn answer(task: &Task, outcome: Outcome) -> Option<ResultBuilder> {
1697    let result = match outcome {
1698        Ok(Ok(reply)) => {
1699            let mut result = TaskResult::success(task.task_id()).echo(task);
1700            if let Some(model_name) = reply.model_name {
1701                result = result.model_name(model_name);
1702            }
1703            reply
1704                .fields
1705                .into_iter()
1706                .fold(result, |result, (name, value)| result.field(name, value))
1707        }
1708        Ok(Err(failure)) => {
1709            let FailureKind::Error { error_type, message } = failure.kind else {
1710                return None;
1711            };
1712            let mut result = TaskResult::failure(task.task_id(), message)
1713                .echo(task)
1714                .error_type(error_type);
1715            if let Some(model_name) = failure.model_name {
1716                result = result.model_name(model_name);
1717            }
1718            failure
1719                .fields
1720                .into_iter()
1721                .fold(result, |result, (name, value)| result.field(name, value))
1722        }
1723        Err(panic) => {
1724            tracing::error!(task_id = task.task_id(), "The handler panicked");
1725            TaskResult::failure(
1726                task.task_id(),
1727                format!("the handler panicked: {}", panic_message(panic.as_ref())),
1728            )
1729            .echo(task)
1730            .error_type(INTERNAL)
1731        }
1732    };
1733    Some(result)
1734}
1735
1736/// Where a result comes from, which decides how one over the worker's limits is cut down.
1737#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1738pub(crate) enum Origin {
1739    /// The handler's reply to a task it ran.
1740    Handler,
1741    /// The worker's own error for an entry it didn't run, such as `invalid_task`.
1742    Refusal,
1743}
1744
1745/// The result's fields, within the limits.
1746///
1747/// A handler's successful reply over the limits becomes a `result_too_large` error, and one that
1748/// still doesn't fit is cut down to its identity and error. A refusal, and a handler's own error,
1749/// keep their error and code whatever they echo: an echo or a field that puts them over the limits
1750/// is dropped, never reported as a `result_too_large` the reply didn't cause.
1751pub(crate) fn result_fields(limits: &Limits, result: ResultBuilder, origin: Origin) -> Vec<(String, String)> {
1752    if origin == Origin::Refusal {
1753        return refusal_fields(limits, result);
1754    }
1755    let fallback = result.clone();
1756    match result.build_within(limits) {
1757        Ok(result) => return result.into_fields(),
1758        // A handler's error keeps its code, shed of what it echoes and carries as a refusal is...
1759        Err(Error::TooLarge { .. }) if fallback.is_error() => return refusal_fields(limits, fallback),
1760        Err(Error::TooLarge { what, limit, actual }) => {
1761            let message = format!("the result's {what} is {actual}, over the limit of {limit}");
1762            let error = fallback.into_error(message, RESULT_TOO_LARGE);
1763            let fields = error.clone().into_fields();
1764            if limits.check(&fields).is_ok() {
1765                return fields;
1766            }
1767            return error.bare().into_fields();
1768        }
1769        // An entry that isn't a valid task has no task to build from...
1770        Err(Error::MissingField(_) | Error::EmptyField(_)) => {}
1771        Err(error) => {
1772            let message = format!("the handler's reply isn't a valid result: {error}");
1773            let error = fallback.into_error(message, INTERNAL);
1774            if let Ok(result) = error.clone().build_within(limits) {
1775                return result.into_fields();
1776            }
1777            return error.bare().into_fields();
1778        }
1779    }
1780    let fields = fallback.clone().into_fields();
1781    if fields::check_strings(&fields, limits).is_ok() {
1782        fields
1783    } else {
1784        fallback.bare().into_fields()
1785    }
1786}
1787
1788/// A refusal's fields within the limits, shrunk one step at a time until they fit: all it
1789/// echoes, then without the optional echoes such as `metadata`, then with each of `model_type`,
1790/// `model_id` and `task_name` replaced by `unknown` when over 1,024 bytes, then with all three
1791/// `unknown`. Every step keeps `model_name` as the task asked; it is emptied only last, when it
1792/// alone doesn't fit. Its status, error and `error_type` are never changed.
1793fn refusal_fields(limits: &Limits, result: ResultBuilder) -> Vec<(String, String)> {
1794    let steps = [
1795        result.clone(),
1796        result.clone().without_echoes(),
1797        result.clone().cut(1024, usize::MAX),
1798        result.clone().cut(0, usize::MAX),
1799    ];
1800    for step in steps {
1801        let fields = step.into_fields();
1802        if fields::check_strings(&fields, limits).is_ok() {
1803            return fields;
1804        }
1805    }
1806    result.cut(0, 0).into_fields()
1807}
1808
1809fn panic_message(panic: &(dyn std::any::Any + Send)) -> &str {
1810    panic
1811        .downcast_ref::<&str>()
1812        .copied()
1813        .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
1814        .unwrap_or("a panic without a message")
1815}