use std::collections::HashMap;
use std::fmt;
use std::panic::{self, AssertUnwindSafe};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread;
use std::time::Duration;
use crate::clock::Clock;
use crate::entry::{Entry, EntryId};
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
use crate::result::{ResultBuilder, Status, TaskResult};
use crate::streams::Streams;
use crate::task::{self, APP_MAX_LEN, REPLY_TO_MAX_LEN, Task};
use crate::worker::{
self, ACTIVE, Context, Control, FINISHING, Flight, Handler, INTERNAL, Origin, Report, Running, Stopper,
};
const REPLY_TO: &str = "reply_to";
const DEADLINE_MS: &str = "deadline_ms";
const READ_RETRY: Duration = Duration::from_millis(500);
pub const KIND_MAX_LEN: usize = 16;
#[must_use]
pub fn is_valid_kind(kind: &str) -> bool {
task::is_name(kind, KIND_MAX_LEN, false)
}
#[must_use]
pub fn rpc_reply_to(app: &str, kind: &str, task_id: &str) -> String {
format!("results:{app}:{kind}:rpc:{task_id}")
}
#[must_use]
pub fn is_valid_rpc_reply_to(reply_to: &str, kind: &str, task_id: &str) -> bool {
if !is_valid_kind(kind) || !task::is_valid_task_id(task_id) || reply_to.len() > REPLY_TO_MAX_LEN {
return false;
}
reply_to
.strip_suffix(task_id)
.and_then(|head| head.strip_prefix("results:"))
.and_then(|head| head.strip_suffix(":rpc:"))
.and_then(|head| head.strip_suffix(kind))
.and_then(|head| head.strip_suffix(':'))
.is_some_and(|app| task::is_name(app, APP_MAX_LEN, false))
}
#[must_use]
pub fn fast_consumer_name(prefix: &str, pid: u32) -> String {
let separator = if prefix.ends_with(['_', '-']) { "" } else { "-" };
format!("{prefix}{separator}fast_{pid}")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FastWorkerConfig {
pub stream: String,
pub group: String,
pub consumer: String,
pub kind: String,
pub concurrency: usize,
pub read_block: Duration,
pub reply_ttl: Duration,
pub limits: Limits,
}
impl FastWorkerConfig {
#[must_use]
pub fn new(
stream: impl Into<String>,
group: impl Into<String>,
consumer: impl Into<String>,
kind: impl Into<String>,
) -> Self {
Self {
stream: stream.into(),
group: group.into(),
consumer: consumer.into(),
kind: kind.into(),
concurrency: 1,
read_block: Duration::from_secs(1),
reply_ttl: Duration::from_secs(60),
limits: Limits::default(),
}
}
fn validate(&self) -> Result<()> {
let invalid = |message: &str| Err(Error::InvalidConfig(message.to_owned()));
for (name, value) in [
("stream", &self.stream),
("group", &self.group),
("consumer", &self.consumer),
] {
if value.is_empty() {
return Err(Error::InvalidConfig(format!("`{name}` is empty")));
}
}
worker::check_task_stream(&self.stream)?;
if !is_valid_kind(&self.kind) {
return invalid("`kind` must be 1 to 16 lowercase ASCII letters, digits, `_` and `-`");
}
if self.concurrency == 0 {
return invalid("`concurrency` is 0; a worker runs at least one task at once");
}
if self.read_block.is_zero() {
return invalid("`read_block` is 0; Redis reads `BLOCK 0` as forever");
}
if self.reply_ttl < Duration::from_secs(1) || self.reply_ttl.subsec_nanos() != 0 {
return invalid("`reply_ttl` must be whole seconds, at least 1; `EXPIRE` takes seconds");
}
Ok(())
}
}
pub struct FastWorker {
config: Arc<FastWorkerConfig>,
streams: Arc<dyn Streams>,
handler: Arc<dyn Handler>,
clock: Clock,
control: Arc<Control>,
}
impl FastWorker {
pub fn new(config: FastWorkerConfig, streams: impl Streams + 'static, handler: impl Handler) -> Result<Self> {
config.validate()?;
let clock = Clock::system();
Ok(Self {
config: Arc::new(config),
streams: Arc::new(streams),
handler: Arc::new(handler),
control: Control::new(&clock),
clock,
})
}
#[must_use]
pub fn clock(mut self, clock: Clock) -> Self {
self.control = Control::new(&clock);
self.clock = clock;
self
}
#[must_use]
pub fn stopper(&self) -> Stopper {
Stopper::new(Arc::clone(&self.control))
}
#[must_use]
pub fn config(&self) -> &FastWorkerConfig {
&self.config
}
pub fn spawn(self) -> Result<Running> {
let stopper = self.stopper();
let thread = thread::Builder::new()
.name("legit-streams-fast".to_owned())
.spawn(move || self.run())
.map_err(|error| Error::Thread(error.to_string()))?;
Ok(Running::new(stopper, thread))
}
pub fn run(&self) -> Result<Report> {
let party = self.clock.party();
party.bind();
let config = &self.config;
self.streams.xgroup_create(&config.stream, &config.group)?;
let run = Arc::new(FastRun {
config: Arc::clone(config),
streams: Arc::clone(&self.streams),
handler: Arc::clone(&self.handler),
clock: self.clock.clone(),
control: Arc::clone(&self.control),
flights: Mutex::new(HashMap::new()),
results: AtomicU64::new(0),
expired: AtomicU64::new(0),
invalid: AtomicU64::new(0),
abandoned: AtomicU64::new(0),
});
tracing::info!(stream = %config.stream, group = %config.group, consumer = %config.consumer, "Fast worker started");
run.read_loop();
run.shut_down();
run.remove_consumer();
let report = Report {
results: run.results.load(Ordering::SeqCst),
expired: run.expired.load(Ordering::SeqCst),
invalid: run.invalid.load(Ordering::SeqCst),
abandoned: run.abandoned.load(Ordering::SeqCst),
..Report::default()
};
tracing::info!(
results = report.results,
expired = report.expired,
invalid = report.invalid,
abandoned = report.abandoned,
"Fast worker stopped"
);
Ok(report)
}
}
impl fmt::Debug for FastWorker {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FastWorker")
.field("config", &self.config)
.field("streams", &self.streams)
.field("clock", &self.clock)
.finish_non_exhaustive()
}
}
struct FastRun {
config: Arc<FastWorkerConfig>,
streams: Arc<dyn Streams>,
handler: Arc<dyn Handler>,
clock: Clock,
control: Arc<Control>,
flights: Mutex<HashMap<EntryId, Arc<Flight>>>,
results: AtomicU64,
expired: AtomicU64,
invalid: AtomicU64,
abandoned: AtomicU64,
}
impl FastRun {
fn stopping(&self) -> bool {
self.control.stopping.load(Ordering::SeqCst)
}
fn lock_flights(&self) -> MutexGuard<'_, HashMap<EntryId, Arc<Flight>>> {
self.flights.lock().unwrap_or_else(PoisonError::into_inner)
}
fn read_loop(self: &Arc<Self>) {
let config = &self.config;
while !self.stopping() {
let seen = self.control.wake.seen();
let free = config.concurrency.saturating_sub(self.lock_flights().len());
if free == 0 {
self.clock.wait(Some((&self.control.wake, seen)), None);
continue;
}
match self.streams.xreadgroup(
&config.stream,
&config.group,
&config.consumer,
free,
Some(config.read_block),
) {
Ok(entries) => {
for entry in entries {
self.admit(entry);
}
}
Err(error) => {
tracing::error!(%error, "Couldn't read fast tasks");
if matches!(error, Error::NoGroup { .. })
&& let Err(error) = self.streams.xgroup_create(&config.stream, &config.group)
{
tracing::error!(%error, "Couldn't create the consumer group again");
}
let deadline = self.clock.monotonic().saturating_add(READ_RETRY);
self.clock.wait(Some((&self.control.wake, seen)), Some(deadline));
}
}
}
}
fn admit(self: &Arc<Self>, entry: Entry) {
let Some(reply_key) = reply_key_of(&entry.fields, &self.config.kind) else {
tracing::warn!(entry = %entry.id, "The entry's `reply_to` isn't the reply key of its `task_id`; deleted unanswered");
self.invalid.fetch_add(1, Ordering::SeqCst);
self.delete(entry.id);
return;
};
match deadline_of(&entry.fields) {
Deadline::At(deadline) if is_past(self.clock.now_ms(), deadline) => {
tracing::debug!(entry = %entry.id, "The entry is past its deadline; deleted unanswered");
self.expired.fetch_add(1, Ordering::SeqCst);
self.delete(entry.id);
return;
}
Deadline::Unreadable => {
tracing::warn!(entry = %entry.id, "The entry's `deadline_ms` isn't a decimal integer; it's taken as no deadline");
}
Deadline::At(_) | Deadline::None => {}
}
self.dispatch(entry, reply_key);
}
fn dispatch(self: &Arc<Self>, entry: Entry, reply_key: String) {
let id = entry.id;
let entry = Arc::new(entry);
let reply_key = Arc::new(reply_key);
let flight = Arc::new(Flight::default());
self.lock_flights().insert(id, Arc::clone(&flight));
let run = Arc::clone(self);
let running = Arc::clone(&flight);
let (task, key) = (Arc::clone(&entry), Arc::clone(&reply_key));
let spawned = thread::Builder::new()
.name("legit-streams-fast-task".to_owned())
.spawn(move || {
run.process(&task, &key, &running);
run.remove_flight(task.id, &running);
run.control.wake.raise();
});
if let Err(error) = spawned {
tracing::error!(entry = %id, %error, "Couldn't start a thread for a fast task");
self.unstarted(&entry, &reply_key, &flight);
self.remove_flight(id, &flight);
}
}
fn unstarted(&self, entry: &Entry, reply_key: &str, flight: &Flight) {
let message = "the worker couldn't start a thread to run the task".to_owned();
let result = ResultBuilder::for_raw(
&entry.fields,
worker::answerable_task_id(&entry.fields),
Status::Error,
message,
)
.error_type(INTERNAL);
self.abandoned.fetch_add(1, Ordering::SeqCst);
self.reply(
entry.id,
flight,
result,
Origin::Refusal,
reply_key,
self.clock.monotonic(),
);
}
fn remove_flight(&self, id: EntryId, flight: &Arc<Flight>) {
let mut flights = self.lock_flights();
if flights.get(&id).is_some_and(|current| Arc::ptr_eq(current, flight)) {
flights.remove(&id);
}
}
fn process(&self, entry: &Entry, reply_key: &str, flight: &Arc<Flight>) {
let started = self.clock.monotonic();
let task = match Task::from_raw(&entry.fields, &self.config.limits) {
Ok(task) => task,
Err(error) => {
tracing::warn!(entry = %entry.id, %error, "The entry isn't a valid task");
let error_type = if matches!(error, Error::UnsupportedVersion(_)) {
worker::UNSUPPORTED_VERSION
} else {
worker::INVALID_TASK
};
let task_id = worker::answerable_task_id(&entry.fields);
let result = ResultBuilder::for_raw(&entry.fields, task_id, Status::Error, error.to_string())
.error_type(error_type);
self.reply(entry.id, flight, result, Origin::Refusal, reply_key, started);
return;
}
};
let context = Context::new(
entry.id,
1,
false,
Arc::clone(flight),
Arc::clone(&self.control),
self.clock.clone(),
started,
);
tracing::debug!(task_id = task.task_id(), entry = %entry.id, "Running a fast task");
let outcome = panic::catch_unwind(AssertUnwindSafe(|| self.handler.handle(&task, &context)));
let result = worker::answer(&task, outcome).unwrap_or_else(|| {
let message = if self.stopping() {
"the worker stopped before the task finished"
} else {
"the handler abandoned the task before it finished"
};
tracing::info!(
task_id = task.task_id(),
"The handler abandoned a fast task; it's answered with an `internal` error"
);
self.abandoned.fetch_add(1, Ordering::SeqCst);
TaskResult::failure(task.task_id(), message)
.echo(&task)
.error_type(INTERNAL)
});
self.reply(entry.id, flight, result, Origin::Handler, reply_key, started);
}
fn reply(
&self,
id: EntryId,
flight: &Flight,
result: ResultBuilder,
origin: Origin,
reply_key: &str,
started: Duration,
) {
if !flight.moves(ACTIVE, FINISHING) {
return;
}
let config = &self.config;
let elapsed = self.clock.monotonic().saturating_sub(started);
let result = result
.worker_id(&config.consumer)
.processing_ms(u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX));
let fields = worker::result_fields(&config.limits, result, origin);
match self
.streams
.xadd_expire(reply_key, &fields::as_bytes(&fields), config.reply_ttl)
{
Ok(_) => {
self.results.fetch_add(1, Ordering::SeqCst);
}
Err(error) => tracing::error!(entry = %id, %error, "Couldn't write a fast reply; its caller times out"),
}
self.delete(id);
}
fn delete(&self, id: EntryId) {
let config = &self.config;
if let Err(error) = self.streams.xack_xdel(&config.stream, &config.group, &[id]) {
tracing::error!(entry = %id, %error, "Couldn't acknowledge a fast task; it stays pending until it's expired");
}
}
fn shut_down(&self) {
loop {
let seen = self.control.wake.seen();
if self.lock_flights().is_empty() {
return;
}
self.clock.wait(Some((&self.control.wake, seen)), None);
}
}
fn remove_consumer(&self) {
let config = &self.config;
match self
.streams
.xpending_consumer(&config.stream, &config.group, &config.consumer, 1)
{
Ok(owned) if owned.is_empty() => {
if let Err(error) = self
.streams
.xgroup_delconsumer(&config.stream, &config.group, &config.consumer)
{
tracing::debug!(%error, "Couldn't remove the consumer");
}
}
Ok(_) => {}
Err(error) => tracing::debug!(%error, "Couldn't check what the consumer owns"),
}
}
}
fn reply_key_of(raw: &[(Vec<u8>, Vec<u8>)], kind: &str) -> Option<String> {
let reply_to = fields::last(raw, REPLY_TO)?;
let task_id = fields::last(raw, "task_id")?;
is_valid_rpc_reply_to(reply_to, kind, task_id).then(|| reply_to.to_owned())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Deadline {
None,
Unreadable,
At(u64),
}
fn deadline_of(raw: &[(Vec<u8>, Vec<u8>)]) -> Deadline {
let Some((_, value)) = raw.iter().rev().find(|(key, _)| key == DEADLINE_MS.as_bytes()) else {
return Deadline::None;
};
if value.is_empty() {
return Deadline::None;
}
if !value.iter().all(u8::is_ascii_digit) {
return Deadline::Unreadable;
}
std::str::from_utf8(value)
.ok()
.and_then(|text| text.parse().ok())
.map_or(Deadline::Unreadable, Deadline::At)
}
const fn is_past(now_ms: u64, deadline: u64) -> bool {
now_ms > deadline
}
#[derive(Clone)]
pub struct FastCaller {
streams: Arc<dyn Streams>,
stream: String,
kind: String,
clock: Clock,
limits: Limits,
}
impl FastCaller {
#[must_use]
pub fn new(streams: impl Streams + 'static, stream: impl Into<String>, kind: impl Into<String>) -> Self {
Self {
streams: Arc::new(streams),
stream: stream.into(),
kind: kind.into(),
clock: Clock::system(),
limits: Limits::default(),
}
}
#[must_use]
pub fn clock(mut self, clock: Clock) -> Self {
self.clock = clock;
self
}
#[must_use]
pub const fn limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
pub fn call(&self, task: &Task, timeout: Duration) -> Result<TaskResult> {
worker::check_task_stream(&self.stream)?;
let timeout = timeout.max(Duration::from_millis(1));
let task_id = task.task_id();
let reply_key = rpc_reply_to(task.source(), &self.kind, task_id);
if !is_valid_rpc_reply_to(&reply_key, &self.kind, task_id) {
return Err(Error::InvalidValue {
field: REPLY_TO.to_owned(),
expected: "`results:<source>:<kind>:rpc:<task_id>`, with a `source` of 1 to 32 and a kind of 1 to 16 \
lowercase ASCII letters, digits, `_` and `-`",
});
}
let timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
let deadline_ms = self.clock.now_ms().saturating_add(timeout_ms);
let fields = request_fields(task, &reply_key, deadline_ms);
fields::check_strings(&fields, &Limits::default())?;
let deadline = self.clock.monotonic().saturating_add(timeout);
let id = self.streams.xadd(&self.stream, &fields::as_bytes(&fields))?;
let mut after = EntryId::ZERO;
loop {
let left = deadline.saturating_sub(self.clock.monotonic());
if left.is_zero() {
self.abandon(id, &reply_key);
return Err(Error::Timeout {
task_id: task_id.to_owned(),
timeout,
});
}
let entry = match self.streams.xread(&reply_key, after, 1, Some(left)) {
Ok(entries) => entries.into_iter().next(),
Err(error) => {
self.abandon(id, &reply_key);
return Err(error);
}
};
let Some(entry) = entry else {
continue;
};
after = entry.id;
match TaskResult::from_raw(&entry.fields, &self.limits) {
Ok(result) if result.task_id() == task_id => {
self.forget(&reply_key);
return Ok(result);
}
Ok(_) => {
tracing::warn!(entry = %entry.id, "An entry on a reply key names another task; it isn't a reply");
}
Err(error) => {
tracing::warn!(entry = %entry.id, %error, "An entry on a reply key isn't a result; it isn't a reply");
}
}
}
}
fn abandon(&self, id: EntryId, reply_key: &str) {
if let Err(error) = self.streams.xdel(&self.stream, &[id]) {
tracing::debug!(%error, "Couldn't take back a fast task; its deadline stops it");
}
self.forget(reply_key);
}
fn forget(&self, reply_key: &str) {
if let Err(error) = self.streams.del(&[reply_key]) {
tracing::debug!(%error, "Couldn't delete a reply key; it expires");
}
}
}
impl fmt::Debug for FastCaller {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FastCaller")
.field("stream", &self.stream)
.field("kind", &self.kind)
.field("clock", &self.clock)
.finish_non_exhaustive()
}
}
fn request_fields(task: &Task, reply_key: &str, deadline_ms: u64) -> Vec<(String, String)> {
let wire = task.wire_fields();
let mut fields = Vec::with_capacity(wire.len() + 2);
for (name, value) in wire {
if name == REPLY_TO || name == DEADLINE_MS {
continue;
}
let version = name == "v";
fields.push((name, value));
if version {
fields.push((REPLY_TO.to_owned(), reply_key.to_owned()));
}
}
fields.push((DEADLINE_MS.to_owned(), deadline_ms.to_string()));
fields
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use super::{Deadline, FastRun, FastWorkerConfig, deadline_of, is_past, rpc_reply_to};
use crate::clock::Clock;
use crate::memory::MemoryStreams;
use crate::result::TaskResult;
use crate::streams::Streams;
use crate::task::Task;
use crate::worker::{Control, Flight, Reply};
#[test]
fn a_task_no_thread_could_be_started_for_is_answered_with_an_internal_error() {
let clock = Clock::manual(1_700_000_000_000);
let streams = MemoryStreams::with_clock(clock.clone());
let config = FastWorkerConfig::new("tasks:fast", "workers", "fast-1", "text");
streams.xgroup_create(&config.stream, &config.group).expect("group");
let key = rpc_reply_to("app", "text", "app_1");
let mut fields = Task::builder("app", "query", "0")
.task_id("app_1")
.build()
.expect("task")
.into_fields();
fields.push(("reply_to".to_owned(), key.clone()));
let pairs: Vec<(&[u8], &[u8])> = fields.iter().map(|(k, v)| (k.as_bytes(), v.as_bytes())).collect();
streams.xadd(&config.stream, &pairs).expect("the request");
let entry = streams
.xreadgroup(&config.stream, &config.group, &config.consumer, 1, None)
.expect("read")
.remove(0);
let run = FastRun {
config: Arc::new(config),
streams: Arc::new(streams.clone()),
handler: Arc::new(|_: &Task, _: &_| Ok(Reply::new())),
control: Control::new(&clock),
clock,
flights: Mutex::new(HashMap::new()),
results: AtomicU64::new(0),
expired: AtomicU64::new(0),
invalid: AtomicU64::new(0),
abandoned: AtomicU64::new(0),
};
run.unstarted(&entry, &key, &Flight::default());
let reply = TaskResult::from_entry(&streams.entries(&key)[0]).expect("one reply");
assert_eq!(reply.task_id(), "app_1");
assert_eq!(reply.error_type(), Some("internal"));
assert_eq!(reply.model_type(), Some("query"));
assert_eq!(streams.xlen("tasks:fast"), Ok(0), "the request is removed");
assert_eq!(
(run.results.load(Ordering::SeqCst), run.abandoned.load(Ordering::SeqCst)),
(1, 1)
);
}
fn raw(value: &[u8]) -> Vec<(Vec<u8>, Vec<u8>)> {
vec![(b"deadline_ms".to_vec(), value.to_vec())]
}
#[test]
fn a_deadline_is_a_plain_decimal_integer() {
assert_eq!(deadline_of(&[]), Deadline::None);
assert_eq!(deadline_of(&raw(b"")), Deadline::None);
assert_eq!(deadline_of(&raw(b"1700000000000")), Deadline::At(1_700_000_000_000));
assert_eq!(deadline_of(&raw(b"0001")), Deadline::At(1));
for unreadable in [
&b" "[..],
b" 1700000000000 ",
b"1.7e12",
b"1700000000000.0",
b"1_700_000_000_000",
b"-5",
b"+5",
b"soon",
b"inf",
b"NaN",
b"0x10",
b"99999999999999999999999",
&[0xff, 0x31],
] {
assert_eq!(
deadline_of(&raw(unreadable)),
Deadline::Unreadable,
"{}",
String::from_utf8_lossy(unreadable)
);
}
let twice = vec![
(b"deadline_ms".to_vec(), b"1".to_vec()),
(b"deadline_ms".to_vec(), b"2".to_vec()),
];
assert_eq!(deadline_of(&twice), Deadline::At(2));
}
#[test]
fn a_deadline_passes_strictly_after_its_millisecond() {
assert!(!is_past(1_000, 1_000));
assert!(is_past(1_001, 1_000));
assert!(!is_past(999, 1_000));
}
}