legit_streams/fast.rs
1//! The fast lane: a request-and-reply path for work done while a caller waits.
2//!
3//! A caller adds a task to a fast task stream with two more fields: `reply_to`, a reply key of its
4//! own, `results:{app}:{kind}:rpc:{task_id}`, and `deadline_ms`, the Unix time in milliseconds after
5//! which it no longer waits. A fast worker reads the stream with a consumer group, deletes what it
6//! can't or needn't answer, and adds one result to each reply key, which then expires. The caller
7//! blocks on its reply key, deletes it, and falls back when nothing came in time.
8
9use std::collections::HashMap;
10use std::fmt;
11use std::panic::{self, AssertUnwindSafe};
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
14use std::thread;
15use std::time::Duration;
16
17use crate::clock::Clock;
18use crate::entry::{Entry, EntryId};
19use crate::error::{Error, Result};
20use crate::fields::{self, Limits};
21use crate::result::{ResultBuilder, Status, TaskResult};
22use crate::streams::Streams;
23use crate::task::{self, APP_MAX_LEN, REPLY_TO_MAX_LEN, Task};
24use crate::worker::{
25 self, ACTIVE, Context, Control, FINISHING, Flight, Handler, INTERNAL, Origin, Report, Running, Stopper,
26};
27
28/// The field naming a fast task's reply key.
29const REPLY_TO: &str = "reply_to";
30/// The field holding a fast task's deadline.
31const DEADLINE_MS: &str = "deadline_ms";
32/// How long the read loop waits after a failed read before it tries again.
33const READ_RETRY: Duration = Duration::from_millis(500);
34
35/// The longest kind of a fast lane, the `{kind}` of its reply keys, in bytes.
36///
37/// ```
38/// assert_eq!(legit_streams::KIND_MAX_LEN, 16);
39/// ```
40pub const KIND_MAX_LEN: usize = 16;
41
42/// Whether `kind` can name a fast lane: 1 to [`KIND_MAX_LEN`] lowercase ASCII letters, digits, `_`
43/// and `-`, such as `hash` or `image`. A [`FastWorker`] and a [`FastCaller`] each serve one kind,
44/// and a worker answers only reply keys of its own.
45///
46/// ```
47/// use legit_streams::is_valid_kind;
48///
49/// assert!(is_valid_kind("hash"));
50/// assert!(!is_valid_kind("Text"));
51/// assert!(!is_valid_kind(""));
52/// assert!(!is_valid_kind("a-kind-of-17-byte"));
53/// ```
54#[must_use]
55pub fn is_valid_kind(kind: &str) -> bool {
56 task::is_name(kind, KIND_MAX_LEN, false)
57}
58
59/// The reply key of a fast task, `results:{app}:{kind}:rpc:{task_id}`: a stream of its own, which
60/// only that task's result is added to. `kind` names the lane, such as `hash`.
61///
62/// ```
63/// assert_eq!(legit_streams::rpc_reply_to("app", "hash", "app_1"), "results:app:hash:rpc:app_1");
64/// ```
65#[must_use]
66pub fn rpc_reply_to(app: &str, kind: &str, task_id: &str) -> String {
67 format!("results:{app}:{kind}:rpc:{task_id}")
68}
69
70/// Whether a fast worker of this `kind` answers a task with this `reply_to` and `task_id`: the key
71/// must be exactly [`rpc_reply_to`]`(app, kind, task_id)` for this task's id and this kind, with
72/// `app` passing [`is_valid_app`](crate::is_valid_app), `task_id` passing
73/// [`is_valid_task_id`](crate::is_valid_task_id), and at most [`REPLY_TO_MAX_LEN`] bytes. Another
74/// task's id, another kind, a bulk reply stream and trailing bytes all fail. A worker deletes a
75/// task whose key fails without answering it: a reply key comes off a queue and names a Redis key,
76/// so it's checked rather than trusted.
77///
78/// ```
79/// use legit_streams::is_valid_rpc_reply_to;
80///
81/// assert!(is_valid_rpc_reply_to("results:app:hash:rpc:app_1", "hash", "app_1"));
82/// assert!(!is_valid_rpc_reply_to("results:app:hash:rpc:app_2", "hash", "app_1"));
83/// assert!(!is_valid_rpc_reply_to("results:app:hash", "hash", "app_1"));
84/// assert!(!is_valid_rpc_reply_to("results:App:hash:rpc:app_1", "hash", "app_1"));
85/// assert!(!is_valid_rpc_reply_to("results:app:image:rpc:app_1", "hash", "app_1"));
86/// assert!(is_valid_rpc_reply_to("results:app:image:rpc:app_1", "image", "app_1"));
87/// ```
88#[must_use]
89pub fn is_valid_rpc_reply_to(reply_to: &str, kind: &str, task_id: &str) -> bool {
90 if !is_valid_kind(kind) || !task::is_valid_task_id(task_id) || reply_to.len() > REPLY_TO_MAX_LEN {
91 return false;
92 }
93 reply_to
94 .strip_suffix(task_id)
95 .and_then(|head| head.strip_prefix("results:"))
96 .and_then(|head| head.strip_suffix(":rpc:"))
97 .and_then(|head| head.strip_suffix(kind))
98 .and_then(|head| head.strip_suffix(':'))
99 .is_some_and(|app| task::is_name(app, APP_MAX_LEN, false))
100}
101
102/// A consumer name for a fast worker, `<prefix>-fast_<pid>`, with no `-` when the prefix already
103/// ends in `-` or `_`. This is the crate's helper, not a rule of the contract: any name unique
104/// within the group works. Sharing a host's prefix keeps a host's consumers together in a listing,
105/// and `fast` keeps it apart from a bulk consumer named `<prefix>_<pid>`.
106///
107/// ```
108/// use legit_streams::fast_consumer_name;
109///
110/// assert_eq!(fast_consumer_name("hash-worker-host1", 4123), "hash-worker-host1-fast_4123");
111/// assert_eq!(fast_consumer_name("hash-worker-", 4123), "hash-worker-fast_4123");
112/// ```
113#[must_use]
114pub fn fast_consumer_name(prefix: &str, pid: u32) -> String {
115 let separator = if prefix.ends_with(['_', '-']) { "" } else { "-" };
116 format!("{prefix}{separator}fast_{pid}")
117}
118
119/// The settings of a [`FastWorker`].
120///
121/// ```
122/// use std::time::Duration;
123/// use legit_streams::FastWorkerConfig;
124///
125/// let config = FastWorkerConfig {
126/// concurrency: 4,
127/// ..FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "hash-worker-host1-fast_4123", "hash")
128/// };
129/// assert_eq!(config.reply_ttl, Duration::from_secs(60));
130/// ```
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct FastWorkerConfig {
133 /// The fast task stream, such as `hash_tasks:fast`. It can't begin with `results:` or `dead:`.
134 pub stream: String,
135 /// The consumer group the worker reads it with, created when missing.
136 pub group: String,
137 /// This worker's consumer name, unique within the group, and the `worker_id` of its results;
138 /// see [`fast_consumer_name`].
139 pub consumer: String,
140 /// The lane's kind, the `{kind}` of the reply keys it answers, such as `hash`; see
141 /// [`is_valid_kind`]. A task whose reply key names another kind is deleted unanswered.
142 pub kind: String,
143 /// How many tasks run at once, each on a thread of its own; also the most one read takes. 1
144 /// by default.
145 pub concurrency: usize,
146 /// How long one read waits for a task; also the longest a stop waits for a read in progress.
147 /// 1 s by default.
148 pub read_block: Duration,
149 /// How long a reply key lives after each reply is added to it, so a reply whose caller gave up
150 /// doesn't stay. Whole seconds, at least 1; 60 s by default, the contract's reference value.
151 pub reply_ttl: Duration,
152 /// The bounds on a task the worker reads and a result it writes.
153 pub limits: Limits,
154}
155
156impl FastWorkerConfig {
157 /// The default settings for reading `stream` with `group` as `consumer`, answering reply keys
158 /// of `kind`. The kind has no default: it's checked when the worker is made.
159 ///
160 /// ```
161 /// use legit_streams::FastWorkerConfig;
162 ///
163 /// let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
164 /// assert_eq!(config.concurrency, 1);
165 /// ```
166 #[must_use]
167 pub fn new(
168 stream: impl Into<String>,
169 group: impl Into<String>,
170 consumer: impl Into<String>,
171 kind: impl Into<String>,
172 ) -> Self {
173 Self {
174 stream: stream.into(),
175 group: group.into(),
176 consumer: consumer.into(),
177 kind: kind.into(),
178 concurrency: 1,
179 read_block: Duration::from_secs(1),
180 reply_ttl: Duration::from_secs(60),
181 limits: Limits::default(),
182 }
183 }
184
185 fn validate(&self) -> Result<()> {
186 let invalid = |message: &str| Err(Error::InvalidConfig(message.to_owned()));
187 for (name, value) in [
188 ("stream", &self.stream),
189 ("group", &self.group),
190 ("consumer", &self.consumer),
191 ] {
192 if value.is_empty() {
193 return Err(Error::InvalidConfig(format!("`{name}` is empty")));
194 }
195 }
196 worker::check_task_stream(&self.stream)?;
197 if !is_valid_kind(&self.kind) {
198 return invalid("`kind` must be 1 to 16 lowercase ASCII letters, digits, `_` and `-`");
199 }
200 if self.concurrency == 0 {
201 return invalid("`concurrency` is 0; a worker runs at least one task at once");
202 }
203 if self.read_block.is_zero() {
204 return invalid("`read_block` is 0; Redis reads `BLOCK 0` as forever");
205 }
206 if self.reply_ttl < Duration::from_secs(1) || self.reply_ttl.subsec_nanos() != 0 {
207 return invalid("`reply_ttl` must be whole seconds, at least 1; `EXPIRE` takes seconds");
208 }
209 Ok(())
210 }
211}
212
213/// The worker side of the fast lane. It reads a fast task stream with a consumer group and answers
214/// each task on the task's own reply key, while its caller waits:
215///
216/// - It creates the group when missing, and again when it goes.
217/// - A task whose `reply_to` fails [`is_valid_rpc_reply_to`] for its `task_id` and the worker's
218/// [`FastWorkerConfig::kind`] is acknowledged and deleted unanswered.
219/// - Then a task whose `deadline_ms`, a plain decimal integer of Unix milliseconds, is before the
220/// worker's clock when it's read is acknowledged and deleted unanswered: its caller has given up.
221/// A clock that reads exactly the deadline still answers. A missing, empty or unreadable deadline
222/// (a sign, a point, an exponent, a blank) is no deadline. The deadline isn't checked again after the work, so a
223/// task that ran past it is still answered.
224/// - Every other entry gets exactly one result, as a [`Worker`](crate::Worker) would write it: the
225/// handler's reply, its error, an `internal` error for a panic, or an error for an entry that
226/// isn't a valid task. The result is added to the reply key, the key's expiry set to
227/// [`FastWorkerConfig::reply_ttl`], and the task acknowledged and deleted, in that order. A write
228/// that fails is logged, not retried: the caller won't wait for a retry.
229/// - A task the worker can't serve gets an error result, not silence: a handler that abandons it
230/// ([`Failure::abandon`](crate::Failure::abandon), or [`Context::checkpoint`] once stopping),
231/// and a task no thread could be started for, are answered with an `internal` error, so the
232/// caller falls back at once.
233/// - Nothing is reclaimed, leased or retried. An entry a dead worker left pending is never run
234/// again; an operator deletes old fast entries, and their callers have timed out.
235/// - On [`Stopper::stop`] it reads no more and answers every task it has read, however long that
236/// takes: a caller may still be waiting. A handler that should stop sooner checks
237/// [`Context::checkpoint`], and its task is answered with an `internal` error. Then the worker
238/// removes its consumer when it owns nothing.
239///
240/// A fast worker runs on threads of its own, so it can run in the same process as a bulk
241/// [`Worker`](crate::Worker), on the same [`Streams`], without waiting for it: a bulk task holds a
242/// bulk slot, never a fast one. Share one handler between them by cloning an `Arc` into each
243/// closure.
244///
245/// ```
246/// use std::time::Duration;
247/// use legit_streams::{Clock, Failure, FastCaller, FastWorker, FastWorkerConfig, MemoryStreams, Reply, Task};
248///
249/// let clock = Clock::manual(1_700_000_000_000);
250/// let streams = MemoryStreams::with_clock(clock.clone());
251/// let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
252/// let running = FastWorker::new(config, streams.clone(), |task: &Task, _: &_| {
253/// let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
254/// Ok(Reply::new().field("result", text.len().to_string()))
255/// })?
256/// .clock(clock.clone())
257/// .spawn()?;
258///
259/// let caller = FastCaller::new(streams.clone(), "hash_tasks:fast", "hash").clock(clock.clone());
260/// let task = Task::builder("app", "query", "0").field("text_data", "hello").build()?;
261/// let result = caller.call(&task, Duration::from_secs(3))?;
262/// assert_eq!(result.get("result"), Some("5"));
263///
264/// running.stop();
265/// clock.advance(Duration::from_secs(1));
266/// assert_eq!(running.join()?.results, 1);
267/// # Ok::<(), legit_streams::Error>(())
268/// ```
269pub struct FastWorker {
270 config: Arc<FastWorkerConfig>,
271 streams: Arc<dyn Streams>,
272 handler: Arc<dyn Handler>,
273 clock: Clock,
274 control: Arc<Control>,
275}
276
277impl FastWorker {
278 /// A fast worker with these settings, on the system clock.
279 ///
280 /// # Errors
281 ///
282 /// [`Error::InvalidConfig`] for settings that can't work, such as an empty stream name, a task
283 /// stream beginning with `results:` or `dead:`, a concurrency of 0, or a reply expiry under a
284 /// second.
285 ///
286 /// ```
287 /// use std::time::Duration;
288 /// use legit_streams::{Error, FastWorker, FastWorkerConfig, MemoryStreams, Reply};
289 ///
290 /// let config = FastWorkerConfig { reply_ttl: Duration::ZERO, ..FastWorkerConfig::new("s", "g", "c", "hash") };
291 /// let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()));
292 /// assert!(matches!(worker, Err(Error::InvalidConfig(_))));
293 /// ```
294 pub fn new(config: FastWorkerConfig, streams: impl Streams + 'static, handler: impl Handler) -> Result<Self> {
295 config.validate()?;
296 let clock = Clock::system();
297 Ok(Self {
298 config: Arc::new(config),
299 streams: Arc::new(streams),
300 handler: Arc::new(handler),
301 control: Control::new(&clock),
302 clock,
303 })
304 }
305
306 /// Run on `clock` rather than the system clock, such as a manual clock in tests: deadlines are
307 /// checked against its time. Take [`FastWorker::stopper`] after this.
308 ///
309 /// ```
310 /// use legit_streams::{Clock, FastWorker, FastWorkerConfig, MemoryStreams, Reply};
311 ///
312 /// let config = FastWorkerConfig::new("s", "g", "c", "hash");
313 /// let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?.clock(Clock::manual(0));
314 /// # Ok::<(), legit_streams::Error>(())
315 /// ```
316 #[must_use]
317 pub fn clock(mut self, clock: Clock) -> Self {
318 self.control = Control::new(&clock);
319 self.clock = clock;
320 self
321 }
322
323 /// The handle that stops this worker.
324 ///
325 /// ```
326 /// use legit_streams::{FastWorker, FastWorkerConfig, MemoryStreams, Reply};
327 ///
328 /// let config = FastWorkerConfig::new("s", "g", "c", "hash");
329 /// let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
330 /// assert!(!worker.stopper().is_stopped());
331 /// # Ok::<(), legit_streams::Error>(())
332 /// ```
333 #[must_use]
334 pub fn stopper(&self) -> Stopper {
335 Stopper::new(Arc::clone(&self.control))
336 }
337
338 /// The worker's settings.
339 ///
340 /// ```
341 /// use legit_streams::{FastWorker, FastWorkerConfig, MemoryStreams, Reply};
342 ///
343 /// let config = FastWorkerConfig::new("s", "g", "c", "hash");
344 /// let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
345 /// assert_eq!(worker.config().consumer, "c");
346 /// # Ok::<(), legit_streams::Error>(())
347 /// ```
348 #[must_use]
349 pub fn config(&self) -> &FastWorkerConfig {
350 &self.config
351 }
352
353 /// Run the worker on a thread of its own.
354 ///
355 /// # Errors
356 ///
357 /// [`Error::Thread`] when the thread can't be started.
358 ///
359 /// ```no_run
360 /// use legit_streams::{FastWorker, FastWorkerConfig, RedisStreams, Reply};
361 ///
362 /// let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
363 /// let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
364 /// let running = FastWorker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?.spawn()?;
365 /// running.stop();
366 /// running.join()?;
367 /// # Ok::<(), legit_streams::Error>(())
368 /// ```
369 pub fn spawn(self) -> Result<Running> {
370 let stopper = self.stopper();
371 let thread = thread::Builder::new()
372 .name("legit-streams-fast".to_owned())
373 .spawn(move || self.run())
374 .map_err(|error| Error::Thread(error.to_string()))?;
375 Ok(Running::new(stopper, thread))
376 }
377
378 /// Run the worker on this thread until [`Stopper::stop`].
379 ///
380 /// # Errors
381 ///
382 /// [`Error::Redis`] when the group can't be created at the start. Once running, a failed
383 /// command is logged and the loop goes on, never returned.
384 ///
385 /// ```no_run
386 /// use legit_streams::{FastWorker, FastWorkerConfig, RedisStreams, Reply};
387 ///
388 /// let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
389 /// let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
390 /// let report = FastWorker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?.run()?;
391 /// println!("{} answered, {} expired", report.results, report.expired);
392 /// # Ok::<(), legit_streams::Error>(())
393 /// ```
394 pub fn run(&self) -> Result<Report> {
395 let party = self.clock.party();
396 party.bind();
397 let config = &self.config;
398 self.streams.xgroup_create(&config.stream, &config.group)?;
399 let run = Arc::new(FastRun {
400 config: Arc::clone(config),
401 streams: Arc::clone(&self.streams),
402 handler: Arc::clone(&self.handler),
403 clock: self.clock.clone(),
404 control: Arc::clone(&self.control),
405 flights: Mutex::new(HashMap::new()),
406 results: AtomicU64::new(0),
407 expired: AtomicU64::new(0),
408 invalid: AtomicU64::new(0),
409 abandoned: AtomicU64::new(0),
410 });
411 tracing::info!(stream = %config.stream, group = %config.group, consumer = %config.consumer, "Fast worker started");
412 run.read_loop();
413 run.shut_down();
414 run.remove_consumer();
415 let report = Report {
416 results: run.results.load(Ordering::SeqCst),
417 expired: run.expired.load(Ordering::SeqCst),
418 invalid: run.invalid.load(Ordering::SeqCst),
419 abandoned: run.abandoned.load(Ordering::SeqCst),
420 ..Report::default()
421 };
422 tracing::info!(
423 results = report.results,
424 expired = report.expired,
425 invalid = report.invalid,
426 abandoned = report.abandoned,
427 "Fast worker stopped"
428 );
429 Ok(report)
430 }
431}
432
433impl fmt::Debug for FastWorker {
434 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435 f.debug_struct("FastWorker")
436 .field("config", &self.config)
437 .field("streams", &self.streams)
438 .field("clock", &self.clock)
439 .finish_non_exhaustive()
440 }
441}
442
443/// One run of a fast worker: what the read loop and the task threads share.
444struct FastRun {
445 config: Arc<FastWorkerConfig>,
446 streams: Arc<dyn Streams>,
447 handler: Arc<dyn Handler>,
448 clock: Clock,
449 control: Arc<Control>,
450 flights: Mutex<HashMap<EntryId, Arc<Flight>>>,
451 results: AtomicU64,
452 expired: AtomicU64,
453 invalid: AtomicU64,
454 abandoned: AtomicU64,
455}
456
457impl FastRun {
458 fn stopping(&self) -> bool {
459 self.control.stopping.load(Ordering::SeqCst)
460 }
461
462 fn lock_flights(&self) -> MutexGuard<'_, HashMap<EntryId, Arc<Flight>>> {
463 self.flights.lock().unwrap_or_else(PoisonError::into_inner)
464 }
465
466 fn read_loop(self: &Arc<Self>) {
467 let config = &self.config;
468 while !self.stopping() {
469 let seen = self.control.wake.seen();
470 let free = config.concurrency.saturating_sub(self.lock_flights().len());
471 if free == 0 {
472 self.clock.wait(Some((&self.control.wake, seen)), None);
473 continue;
474 }
475 match self.streams.xreadgroup(
476 &config.stream,
477 &config.group,
478 &config.consumer,
479 free,
480 Some(config.read_block),
481 ) {
482 // A worker asked to stop answers what it has read...
483 Ok(entries) => {
484 for entry in entries {
485 self.admit(entry);
486 }
487 }
488 Err(error) => {
489 tracing::error!(%error, "Couldn't read fast tasks");
490 if matches!(error, Error::NoGroup { .. })
491 && let Err(error) = self.streams.xgroup_create(&config.stream, &config.group)
492 {
493 tracing::error!(%error, "Couldn't create the consumer group again");
494 }
495 let deadline = self.clock.monotonic().saturating_add(READ_RETRY);
496 self.clock.wait(Some((&self.control.wake, seen)), Some(deadline));
497 }
498 }
499 }
500 }
501
502 /// Check an entry's reply key and deadline, then run it or delete it.
503 fn admit(self: &Arc<Self>, entry: Entry) {
504 let Some(reply_key) = reply_key_of(&entry.fields, &self.config.kind) else {
505 tracing::warn!(entry = %entry.id, "The entry's `reply_to` isn't the reply key of its `task_id`; deleted unanswered");
506 self.invalid.fetch_add(1, Ordering::SeqCst);
507 self.delete(entry.id);
508 return;
509 };
510 match deadline_of(&entry.fields) {
511 Deadline::At(deadline) if is_past(self.clock.now_ms(), deadline) => {
512 tracing::debug!(entry = %entry.id, "The entry is past its deadline; deleted unanswered");
513 self.expired.fetch_add(1, Ordering::SeqCst);
514 self.delete(entry.id);
515 return;
516 }
517 Deadline::Unreadable => {
518 tracing::warn!(entry = %entry.id, "The entry's `deadline_ms` isn't a decimal integer; it's taken as no deadline");
519 }
520 Deadline::At(_) | Deadline::None => {}
521 }
522 self.dispatch(entry, reply_key);
523 }
524
525 fn dispatch(self: &Arc<Self>, entry: Entry, reply_key: String) {
526 let id = entry.id;
527 let entry = Arc::new(entry);
528 let reply_key = Arc::new(reply_key);
529 let flight = Arc::new(Flight::default());
530 self.lock_flights().insert(id, Arc::clone(&flight));
531 let run = Arc::clone(self);
532 let running = Arc::clone(&flight);
533 let (task, key) = (Arc::clone(&entry), Arc::clone(&reply_key));
534 let spawned = thread::Builder::new()
535 .name("legit-streams-fast-task".to_owned())
536 .spawn(move || {
537 run.process(&task, &key, &running);
538 run.remove_flight(task.id, &running);
539 run.control.wake.raise();
540 });
541 if let Err(error) = spawned {
542 tracing::error!(entry = %id, %error, "Couldn't start a thread for a fast task");
543 self.unstarted(&entry, &reply_key, &flight);
544 self.remove_flight(id, &flight);
545 }
546 }
547
548 /// Answer a task no thread could be started for with an `internal` error, so its caller falls
549 /// back at once rather than at its timeout.
550 fn unstarted(&self, entry: &Entry, reply_key: &str, flight: &Flight) {
551 let message = "the worker couldn't start a thread to run the task".to_owned();
552 let result = ResultBuilder::for_raw(
553 &entry.fields,
554 worker::answerable_task_id(&entry.fields),
555 Status::Error,
556 message,
557 )
558 .error_type(INTERNAL);
559 self.abandoned.fetch_add(1, Ordering::SeqCst);
560 self.reply(
561 entry.id,
562 flight,
563 result,
564 Origin::Refusal,
565 reply_key,
566 self.clock.monotonic(),
567 );
568 }
569
570 fn remove_flight(&self, id: EntryId, flight: &Arc<Flight>) {
571 let mut flights = self.lock_flights();
572 if flights.get(&id).is_some_and(|current| Arc::ptr_eq(current, flight)) {
573 flights.remove(&id);
574 }
575 }
576
577 fn process(&self, entry: &Entry, reply_key: &str, flight: &Arc<Flight>) {
578 let started = self.clock.monotonic();
579 let task = match Task::from_raw(&entry.fields, &self.config.limits) {
580 Ok(task) => task,
581 Err(error) => {
582 tracing::warn!(entry = %entry.id, %error, "The entry isn't a valid task");
583 let error_type = if matches!(error, Error::UnsupportedVersion(_)) {
584 worker::UNSUPPORTED_VERSION
585 } else {
586 worker::INVALID_TASK
587 };
588 let task_id = worker::answerable_task_id(&entry.fields);
589 let result = ResultBuilder::for_raw(&entry.fields, task_id, Status::Error, error.to_string())
590 .error_type(error_type);
591 self.reply(entry.id, flight, result, Origin::Refusal, reply_key, started);
592 return;
593 }
594 };
595 // Read with `>` and never claimed, so this is always the first delivery...
596 let context = Context::new(
597 entry.id,
598 1,
599 false,
600 Arc::clone(flight),
601 Arc::clone(&self.control),
602 self.clock.clone(),
603 started,
604 );
605 tracing::debug!(task_id = task.task_id(), entry = %entry.id, "Running a fast task");
606 let outcome = panic::catch_unwind(AssertUnwindSafe(|| self.handler.handle(&task, &context)));
607 let result = worker::answer(&task, outcome).unwrap_or_else(|| {
608 // A fast task gets one result, even one its handler abandoned...
609 let message = if self.stopping() {
610 "the worker stopped before the task finished"
611 } else {
612 "the handler abandoned the task before it finished"
613 };
614 tracing::info!(
615 task_id = task.task_id(),
616 "The handler abandoned a fast task; it's answered with an `internal` error"
617 );
618 self.abandoned.fetch_add(1, Ordering::SeqCst);
619 TaskResult::failure(task.task_id(), message)
620 .echo(&task)
621 .error_type(INTERNAL)
622 });
623 self.reply(entry.id, flight, result, Origin::Handler, reply_key, started);
624 }
625
626 /// Add the result to the reply key and set its expiry, then acknowledge and delete the task.
627 fn reply(
628 &self,
629 id: EntryId,
630 flight: &Flight,
631 result: ResultBuilder,
632 origin: Origin,
633 reply_key: &str,
634 started: Duration,
635 ) {
636 if !flight.moves(ACTIVE, FINISHING) {
637 return;
638 }
639 let config = &self.config;
640 let elapsed = self.clock.monotonic().saturating_sub(started);
641 let result = result
642 .worker_id(&config.consumer)
643 .processing_ms(u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX));
644 let fields = worker::result_fields(&config.limits, result, origin);
645 match self
646 .streams
647 .xadd_expire(reply_key, &fields::as_bytes(&fields), config.reply_ttl)
648 {
649 Ok(_) => {
650 self.results.fetch_add(1, Ordering::SeqCst);
651 }
652 Err(error) => tracing::error!(entry = %id, %error, "Couldn't write a fast reply; its caller times out"),
653 }
654 // Acknowledged either way: no one would ever answer it...
655 self.delete(id);
656 }
657
658 /// Acknowledge and delete an entry; nothing reclaims a fast entry, so it's never left pending.
659 fn delete(&self, id: EntryId) {
660 let config = &self.config;
661 if let Err(error) = self.streams.xack_xdel(&config.stream, &config.group, &[id]) {
662 tracing::error!(entry = %id, %error, "Couldn't acknowledge a fast task; it stays pending until it's expired");
663 }
664 }
665
666 /// Wait for every task the worker has read to finish and be answered, however long it takes:
667 /// a worker asked to stop answers what it has read, since a caller may still be waiting.
668 fn shut_down(&self) {
669 loop {
670 let seen = self.control.wake.seen();
671 if self.lock_flights().is_empty() {
672 return;
673 }
674 self.clock.wait(Some((&self.control.wake, seen)), None);
675 }
676 }
677
678 /// Remove this worker's consumer from the group, unless it still owns entries.
679 fn remove_consumer(&self) {
680 let config = &self.config;
681 match self
682 .streams
683 .xpending_consumer(&config.stream, &config.group, &config.consumer, 1)
684 {
685 Ok(owned) if owned.is_empty() => {
686 if let Err(error) = self
687 .streams
688 .xgroup_delconsumer(&config.stream, &config.group, &config.consumer)
689 {
690 tracing::debug!(%error, "Couldn't remove the consumer");
691 }
692 }
693 Ok(_) => {}
694 Err(error) => tracing::debug!(%error, "Couldn't check what the consumer owns"),
695 }
696 }
697}
698
699/// The entry's reply key, when it's the valid one for its task id and this lane's kind.
700fn reply_key_of(raw: &[(Vec<u8>, Vec<u8>)], kind: &str) -> Option<String> {
701 let reply_to = fields::last(raw, REPLY_TO)?;
702 let task_id = fields::last(raw, "task_id")?;
703 is_valid_rpc_reply_to(reply_to, kind, task_id).then(|| reply_to.to_owned())
704}
705
706/// A fast task's deadline.
707#[derive(Debug, Clone, Copy, PartialEq, Eq)]
708enum Deadline {
709 /// No `deadline_ms`, or an empty one.
710 None,
711 /// A `deadline_ms` that isn't a plain decimal integer, which counts as none.
712 Unreadable,
713 /// Unix time in milliseconds.
714 At(u64),
715}
716
717fn deadline_of(raw: &[(Vec<u8>, Vec<u8>)]) -> Deadline {
718 let Some((_, value)) = raw.iter().rev().find(|(key, _)| key == DEADLINE_MS.as_bytes()) else {
719 return Deadline::None;
720 };
721 if value.is_empty() {
722 return Deadline::None;
723 }
724 // A plain decimal integer: digits only, no sign, blank, point or exponent...
725 if !value.iter().all(u8::is_ascii_digit) {
726 return Deadline::Unreadable;
727 }
728 std::str::from_utf8(value)
729 .ok()
730 .and_then(|text| text.parse().ok())
731 .map_or(Deadline::Unreadable, Deadline::At)
732}
733
734/// Whether `now_ms` is past a deadline: strictly after it, so a worker whose clock reads exactly
735/// the deadline still answers. There is no tolerance either way.
736const fn is_past(now_ms: u64, deadline: u64) -> bool {
737 now_ms > deadline
738}
739
740/// Sends fast-lane tasks and waits for their replies.
741///
742/// [`FastCaller::call`] adds the task to the fast task stream with a reply key of its own and a
743/// deadline, blocks on the reply key, deletes it, and returns the result, or
744/// [`Error::Timeout`] when none came in time. See [`FastWorker`] for a full exchange.
745///
746/// ```
747/// use std::time::Duration;
748/// use legit_streams::{Error, FastCaller, MemoryStreams, Task};
749///
750/// // No worker serves this stream, so the call times out...
751/// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "hash");
752/// let task = Task::builder("app", "query", "0").field("text_data", "hello").build()?;
753/// match caller.call(&task, Duration::from_millis(5)) {
754/// Err(Error::Timeout { .. }) => { /* fall back */ }
755/// other => panic!("{other:?}"),
756/// }
757/// # Ok::<(), legit_streams::Error>(())
758/// ```
759#[derive(Clone)]
760pub struct FastCaller {
761 streams: Arc<dyn Streams>,
762 stream: String,
763 kind: String,
764 clock: Clock,
765 limits: Limits,
766}
767
768impl FastCaller {
769 /// A caller sending to the fast task stream `stream`, for the fast lane of `kind`, the
770 /// `{kind}` of its reply keys, on the system clock. The kind has no default: a call checks it
771 /// with [`is_valid_kind`].
772 ///
773 /// ```
774 /// use legit_streams::{FastCaller, MemoryStreams};
775 ///
776 /// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "hash");
777 /// # let _ = caller;
778 /// ```
779 #[must_use]
780 pub fn new(streams: impl Streams + 'static, stream: impl Into<String>, kind: impl Into<String>) -> Self {
781 Self {
782 streams: Arc::new(streams),
783 stream: stream.into(),
784 kind: kind.into(),
785 clock: Clock::system(),
786 limits: Limits::default(),
787 }
788 }
789
790 /// Take deadlines from `clock` rather than the system clock, such as a manual clock in tests.
791 ///
792 /// ```
793 /// use legit_streams::{Clock, FastCaller, MemoryStreams};
794 ///
795 /// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "hash").clock(Clock::manual(0));
796 /// # let _ = caller;
797 /// ```
798 #[must_use]
799 pub fn clock(mut self, clock: Clock) -> Self {
800 self.clock = clock;
801 self
802 }
803
804 /// Set the bounds on a reply entry.
805 ///
806 /// ```
807 /// use legit_streams::{FastCaller, Limits, MemoryStreams};
808 ///
809 /// let limits = Limits { max_entry_bytes: 1024 * 1024, ..Limits::default() };
810 /// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "hash").limits(limits);
811 /// # let _ = caller;
812 /// ```
813 #[must_use]
814 pub const fn limits(mut self, limits: Limits) -> Self {
815 self.limits = limits;
816 self
817 }
818
819 /// Send `task` and wait up to `timeout` for its result.
820 ///
821 /// The task goes to the fast task stream with two fields set, replacing any it has:
822 /// `reply_to`, its reply key [`rpc_reply_to`]`(source, kind, task_id)`, right after `v`, and
823 /// `deadline_ms`, the caller's clock plus `timeout` in Unix milliseconds, last. The call then
824 /// reads the reply key from its start, `XREAD … BLOCK <ms> STREAMS <key> 0`: the key is this
825 /// call's alone, so a reply that arrived before the read began is the first entry there, and
826 /// none is missed. Once a reply is read, or the wait ends, the key is deleted. A timeout under
827 /// a millisecond waits a millisecond.
828 ///
829 /// A reply counts only when it's a result whose `task_id` is the task's own and whose `status`
830 /// is exactly `success` or `error`. Anything else on the key isn't a reply: the call logs it,
831 /// skips it and goes on reading the key until the deadline, so a stray entry ends as a timeout,
832 /// never as a result.
833 ///
834 /// The result comes back as it was written, success or error: check
835 /// [`TaskResult::is_success`].
836 ///
837 /// The task's id must carry at least 64 random bits, as the `{app}_{ULID}` id the builder
838 /// generates does: the reply key is named after it, and an id another party can guess is a
839 /// key it can answer. A caller that sets its own id with
840 /// [`TaskBuilder::task_id`](crate::TaskBuilder::task_id) owns that.
841 ///
842 /// # Errors
843 ///
844 /// - [`Error::Timeout`] when no reply came within `timeout`. The call has deleted its task
845 /// from the stream, so no worker starts it, and its reply key, and a reply that comes later
846 /// expires with the key. Fall back.
847 /// - [`Error::InvalidConfig`] when the caller's stream begins with `results:` or `dead:`, and
848 /// [`Error::InvalidValue`] when the reply key wouldn't pass [`is_valid_rpc_reply_to`], such
849 /// as for a caller whose kind fails [`is_valid_kind`]; nothing is sent.
850 /// - [`Error::TooLarge`] when the request, the task with `reply_to`, `deadline_ms` and, for a
851 /// task read without one, `v` added, is over the default [`Limits`]; nothing is sent.
852 /// - [`Error::Redis`] when the task can't be sent or the key can't be read; after a failed
853 /// read the task and key are deleted as on a timeout.
854 ///
855 /// ```
856 /// use std::time::Duration;
857 /// use legit_streams::{Error, FastCaller, MemoryStreams, Task};
858 ///
859 /// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "Text");
860 /// let task = Task::builder("app", "query", "0").build()?;
861 /// assert!(matches!(caller.call(&task, Duration::from_secs(1)), Err(Error::InvalidValue { .. })));
862 ///
863 /// let caller = FastCaller::new(MemoryStreams::new(), "results:app:hash", "hash");
864 /// assert!(matches!(caller.call(&task, Duration::from_secs(1)), Err(Error::InvalidConfig(_))));
865 /// # Ok::<(), legit_streams::Error>(())
866 /// ```
867 pub fn call(&self, task: &Task, timeout: Duration) -> Result<TaskResult> {
868 worker::check_task_stream(&self.stream)?;
869 let timeout = timeout.max(Duration::from_millis(1));
870 let task_id = task.task_id();
871 let reply_key = rpc_reply_to(task.source(), &self.kind, task_id);
872 if !is_valid_rpc_reply_to(&reply_key, &self.kind, task_id) {
873 return Err(Error::InvalidValue {
874 field: REPLY_TO.to_owned(),
875 expected: "`results:<source>:<kind>:rpc:<task_id>`, with a `source` of 1 to 32 and a kind of 1 to 16 \
876 lowercase ASCII letters, digits, `_` and `-`",
877 });
878 }
879 let timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
880 let deadline_ms = self.clock.now_ms().saturating_add(timeout_ms);
881 let fields = request_fields(task, &reply_key, deadline_ms);
882 // The added fields can take a task at a bound over it, and a worker would refuse it...
883 fields::check_strings(&fields, &Limits::default())?;
884 let deadline = self.clock.monotonic().saturating_add(timeout);
885 let id = self.streams.xadd(&self.stream, &fields::as_bytes(&fields))?;
886 let mut after = EntryId::ZERO;
887 loop {
888 let left = deadline.saturating_sub(self.clock.monotonic());
889 if left.is_zero() {
890 self.abandon(id, &reply_key);
891 return Err(Error::Timeout {
892 task_id: task_id.to_owned(),
893 timeout,
894 });
895 }
896 let entry = match self.streams.xread(&reply_key, after, 1, Some(left)) {
897 Ok(entries) => entries.into_iter().next(),
898 Err(error) => {
899 self.abandon(id, &reply_key);
900 return Err(error);
901 }
902 };
903 let Some(entry) = entry else {
904 continue;
905 };
906 after = entry.id;
907 match TaskResult::from_raw(&entry.fields, &self.limits) {
908 Ok(result) if result.task_id() == task_id => {
909 self.forget(&reply_key);
910 return Ok(result);
911 }
912 Ok(_) => {
913 tracing::warn!(entry = %entry.id, "An entry on a reply key names another task; it isn't a reply");
914 }
915 Err(error) => {
916 tracing::warn!(entry = %entry.id, %error, "An entry on a reply key isn't a result; it isn't a reply");
917 }
918 }
919 }
920 }
921
922 /// Take the task back, so no worker starts it, and delete the reply key. Best effort: a
923 /// worker skips the task once its deadline passes, and a late reply expires.
924 fn abandon(&self, id: EntryId, reply_key: &str) {
925 if let Err(error) = self.streams.xdel(&self.stream, &[id]) {
926 tracing::debug!(%error, "Couldn't take back a fast task; its deadline stops it");
927 }
928 self.forget(reply_key);
929 }
930
931 fn forget(&self, reply_key: &str) {
932 if let Err(error) = self.streams.del(&[reply_key]) {
933 tracing::debug!(%error, "Couldn't delete a reply key; it expires");
934 }
935 }
936}
937
938impl fmt::Debug for FastCaller {
939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940 f.debug_struct("FastCaller")
941 .field("stream", &self.stream)
942 .field("kind", &self.kind)
943 .field("clock", &self.clock)
944 .finish_non_exhaustive()
945 }
946}
947
948/// The fields of a fast request: the task's, with `v` = `1` (added after `source` when a task
949/// read from an older producer had none), `reply_to` after `v` and `deadline_ms` last.
950fn request_fields(task: &Task, reply_key: &str, deadline_ms: u64) -> Vec<(String, String)> {
951 let wire = task.wire_fields();
952 let mut fields = Vec::with_capacity(wire.len() + 2);
953 for (name, value) in wire {
954 if name == REPLY_TO || name == DEADLINE_MS {
955 continue;
956 }
957 let version = name == "v";
958 fields.push((name, value));
959 if version {
960 fields.push((REPLY_TO.to_owned(), reply_key.to_owned()));
961 }
962 }
963 fields.push((DEADLINE_MS.to_owned(), deadline_ms.to_string()));
964 fields
965}
966
967#[cfg(test)]
968mod tests {
969 use std::collections::HashMap;
970 use std::sync::atomic::{AtomicU64, Ordering};
971 use std::sync::{Arc, Mutex};
972
973 use super::{Deadline, FastRun, FastWorkerConfig, deadline_of, is_past, rpc_reply_to};
974 use crate::clock::Clock;
975 use crate::memory::MemoryStreams;
976 use crate::result::TaskResult;
977 use crate::streams::Streams;
978 use crate::task::Task;
979 use crate::worker::{Control, Flight, Reply};
980
981 #[test]
982 fn a_task_no_thread_could_be_started_for_is_answered_with_an_internal_error() {
983 let clock = Clock::manual(1_700_000_000_000);
984 let streams = MemoryStreams::with_clock(clock.clone());
985 let config = FastWorkerConfig::new("tasks:fast", "workers", "fast-1", "text");
986 streams.xgroup_create(&config.stream, &config.group).expect("group");
987 let key = rpc_reply_to("app", "text", "app_1");
988 let mut fields = Task::builder("app", "query", "0")
989 .task_id("app_1")
990 .build()
991 .expect("task")
992 .into_fields();
993 fields.push(("reply_to".to_owned(), key.clone()));
994 let pairs: Vec<(&[u8], &[u8])> = fields.iter().map(|(k, v)| (k.as_bytes(), v.as_bytes())).collect();
995 streams.xadd(&config.stream, &pairs).expect("the request");
996 let entry = streams
997 .xreadgroup(&config.stream, &config.group, &config.consumer, 1, None)
998 .expect("read")
999 .remove(0);
1000 let run = FastRun {
1001 config: Arc::new(config),
1002 streams: Arc::new(streams.clone()),
1003 handler: Arc::new(|_: &Task, _: &_| Ok(Reply::new())),
1004 control: Control::new(&clock),
1005 clock,
1006 flights: Mutex::new(HashMap::new()),
1007 results: AtomicU64::new(0),
1008 expired: AtomicU64::new(0),
1009 invalid: AtomicU64::new(0),
1010 abandoned: AtomicU64::new(0),
1011 };
1012 run.unstarted(&entry, &key, &Flight::default());
1013
1014 let reply = TaskResult::from_entry(&streams.entries(&key)[0]).expect("one reply");
1015 assert_eq!(reply.task_id(), "app_1");
1016 assert_eq!(reply.error_type(), Some("internal"));
1017 assert_eq!(reply.model_type(), Some("query"));
1018 assert_eq!(streams.xlen("tasks:fast"), Ok(0), "the request is removed");
1019 assert_eq!(
1020 (run.results.load(Ordering::SeqCst), run.abandoned.load(Ordering::SeqCst)),
1021 (1, 1)
1022 );
1023 }
1024
1025 fn raw(value: &[u8]) -> Vec<(Vec<u8>, Vec<u8>)> {
1026 vec![(b"deadline_ms".to_vec(), value.to_vec())]
1027 }
1028
1029 #[test]
1030 fn a_deadline_is_a_plain_decimal_integer() {
1031 assert_eq!(deadline_of(&[]), Deadline::None);
1032 assert_eq!(deadline_of(&raw(b"")), Deadline::None);
1033 assert_eq!(deadline_of(&raw(b"1700000000000")), Deadline::At(1_700_000_000_000));
1034 assert_eq!(deadline_of(&raw(b"0001")), Deadline::At(1));
1035 for unreadable in [
1036 &b" "[..],
1037 b" 1700000000000 ",
1038 b"1.7e12",
1039 b"1700000000000.0",
1040 b"1_700_000_000_000",
1041 b"-5",
1042 b"+5",
1043 b"soon",
1044 b"inf",
1045 b"NaN",
1046 b"0x10",
1047 b"99999999999999999999999",
1048 &[0xff, 0x31],
1049 ] {
1050 assert_eq!(
1051 deadline_of(&raw(unreadable)),
1052 Deadline::Unreadable,
1053 "{}",
1054 String::from_utf8_lossy(unreadable)
1055 );
1056 }
1057 // A later field replaces an earlier one, as a reader of repeated names takes the last...
1058 let twice = vec![
1059 (b"deadline_ms".to_vec(), b"1".to_vec()),
1060 (b"deadline_ms".to_vec(), b"2".to_vec()),
1061 ];
1062 assert_eq!(deadline_of(&twice), Deadline::At(2));
1063 }
1064
1065 #[test]
1066 fn a_deadline_passes_strictly_after_its_millisecond() {
1067 assert!(!is_past(1_000, 1_000));
1068 assert!(is_past(1_001, 1_000));
1069 assert!(!is_past(999, 1_000));
1070 }
1071}