use std::collections::HashMap;
use std::fmt;
use std::panic::{self, AssertUnwindSafe};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use crate::clock::{Clock, Signal};
use crate::entry::{Entry, EntryId, LostLease, Renewal};
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
use crate::result::{ResultBuilder, Status, TaskResult};
use crate::streams::Streams;
use crate::task::{Task, is_valid_reply_to};
pub const UNSUPPORTED_MODEL: &str = "unsupported_model";
pub const INVALID_DIMENSIONS: &str = "invalid_dimensions";
pub const INVALID_OPTIONS: &str = "invalid_options";
pub const INVALID_EMBED_ROLE: &str = "invalid_embed_role";
pub const MODEL_UNAVAILABLE: &str = "model_unavailable";
pub const DOWNLOAD_FAILED: &str = "download_failed";
pub const URL_EXPIRED: &str = "url_expired";
pub const DECODE_FAILED: &str = "decode_failed";
pub const DIARIZE_FAILED: &str = "diarize_failed";
pub const ASR_FAILED: &str = "asr_failed";
pub const INVALID_TASK: &str = "invalid_task";
pub const UNSUPPORTED_VERSION: &str = "unsupported_version";
pub const MAX_DELIVERIES_EXCEEDED: &str = "max_deliveries_exceeded";
pub const INTERNAL: &str = "internal";
pub const RESULT_TOO_LARGE: &str = "result_too_large";
const READ_RETRY: Duration = Duration::from_secs(1);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkerConfig {
pub stream: String,
pub group: String,
pub consumer: String,
pub result_stream: String,
pub route_results_per_app: bool,
pub concurrency: usize,
pub read_block: Duration,
pub lease_heartbeat: Duration,
pub claim_idle: Duration,
pub max_deliveries: u64,
pub shutdown_grace: Duration,
pub flush_attempts: u32,
pub flush_backoff: Duration,
pub limits: Limits,
}
impl WorkerConfig {
#[must_use]
pub fn new(
stream: impl Into<String>,
group: impl Into<String>,
consumer: impl Into<String>,
result_stream: impl Into<String>,
) -> Self {
Self {
stream: stream.into(),
group: group.into(),
consumer: consumer.into(),
result_stream: result_stream.into(),
route_results_per_app: true,
concurrency: 1,
read_block: Duration::from_secs(5),
lease_heartbeat: Duration::from_secs(60),
claim_idle: Duration::from_secs(300),
max_deliveries: 3,
shutdown_grace: Duration::from_secs(30),
flush_attempts: 5,
flush_backoff: Duration::from_secs(2),
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),
("result_stream", &self.result_stream),
] {
if value.is_empty() {
return Err(Error::InvalidConfig(format!("`{name}` is empty")));
}
}
check_task_stream(&self.stream)?;
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.lease_heartbeat.is_zero() || self.lease_heartbeat.saturating_mul(3) > self.claim_idle {
return invalid(
"`lease_heartbeat` must be above 0 and at most a third of `claim_idle`, so a worker can miss two \
renewals before another claims its task",
);
}
if self.max_deliveries == 0 {
return invalid("`max_deliveries` is 0; a task needs one delivery to run");
}
if self.flush_attempts == 0 {
return invalid("`flush_attempts` is 0; a result needs one attempt to be written");
}
Ok(())
}
}
pub(crate) fn check_task_stream(stream: &str) -> Result<()> {
for reserved in ["results:", "dead:"] {
if stream.starts_with(reserved) {
return Err(Error::InvalidConfig(format!(
"the task stream `{stream}` begins with `{reserved}`, which no task stream may"
)));
}
}
Ok(())
}
const ANSWERED_TASK_ID_MAX_LEN: usize = 256;
pub(crate) fn answerable_task_id(raw: &[(Vec<u8>, Vec<u8>)]) -> Option<&str> {
fields::last(raw, "task_id").filter(|id| !id.is_empty() && id.len() <= ANSWERED_TASK_ID_MAX_LEN)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Reply {
model_name: Option<String>,
fields: Vec<(String, String)>,
}
impl Reply {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.fields.push((name.into(), value.into()));
self
}
#[must_use]
pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
self.model_name = Some(model_name.into());
self
}
#[must_use]
pub fn fields(&self) -> &[(String, String)] {
&self.fields
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
kind: FailureKind,
model_name: Option<String>,
fields: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum FailureKind {
Error { error_type: String, message: String },
Abandon { reason: String },
}
impl Failure {
#[must_use]
pub fn new(error_type: impl Into<String>, message: impl Into<String>) -> Self {
Self::of(FailureKind::Error {
error_type: error_type.into(),
message: message.into(),
})
}
#[must_use]
pub fn abandon(reason: impl Into<String>) -> Self {
Self::of(FailureKind::Abandon { reason: reason.into() })
}
const fn of(kind: FailureKind) -> Self {
Self {
kind,
model_name: None,
fields: Vec::new(),
}
}
#[must_use]
pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.fields.push((name.into(), value.into()));
self
}
#[must_use]
pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
self.model_name = Some(model_name.into());
self
}
#[must_use]
pub const fn is_abandon(&self) -> bool {
matches!(self.kind, FailureKind::Abandon { .. })
}
#[must_use]
pub fn error_type(&self) -> Option<&str> {
match &self.kind {
FailureKind::Error { error_type, .. } => Some(error_type),
FailureKind::Abandon { .. } => None,
}
}
#[must_use]
pub fn message(&self) -> &str {
match &self.kind {
FailureKind::Error { message, .. } => message,
FailureKind::Abandon { reason } => reason,
}
}
}
pub trait Handler: Send + Sync + 'static {
fn handle(&self, task: &Task, context: &Context) -> std::result::Result<Reply, Failure>;
}
impl<F> Handler for F
where
F: Fn(&Task, &Context) -> std::result::Result<Reply, Failure> + Send + Sync + 'static,
{
fn handle(&self, task: &Task, context: &Context) -> std::result::Result<Reply, Failure> {
self(task, context)
}
}
pub struct Context {
entry_id: EntryId,
deliveries: u64,
reclaimed: bool,
flight: Arc<Flight>,
control: Arc<Control>,
clock: Clock,
started: Duration,
}
impl Context {
pub(crate) const fn new(
entry_id: EntryId,
deliveries: u64,
reclaimed: bool,
flight: Arc<Flight>,
control: Arc<Control>,
clock: Clock,
started: Duration,
) -> Self {
Self {
entry_id,
deliveries,
reclaimed,
flight,
control,
clock,
started,
}
}
#[must_use]
pub fn elapsed(&self) -> Duration {
self.clock.monotonic().saturating_sub(self.started)
}
#[must_use]
pub const fn entry_id(&self) -> EntryId {
self.entry_id
}
#[must_use]
pub const fn deliveries(&self) -> u64 {
self.deliveries
}
#[must_use]
pub const fn is_reclaimed(&self) -> bool {
self.reclaimed
}
#[must_use]
pub fn is_stopping(&self) -> bool {
self.control.stopping.load(Ordering::SeqCst)
}
#[must_use]
pub fn is_lease_lost(&self) -> bool {
self.flight.lost.load(Ordering::SeqCst)
}
pub fn checkpoint(&self) -> std::result::Result<(), Failure> {
if self.is_stopping() {
return Err(Failure::abandon("the worker is stopping"));
}
if self.is_lease_lost() {
return Err(Failure::abandon("the lease on the task was lost"));
}
Ok(())
}
}
impl fmt::Debug for Context {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Context")
.field("entry_id", &self.entry_id)
.field("deliveries", &self.deliveries)
.field("reclaimed", &self.reclaimed)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct Stopper {
control: Arc<Control>,
}
impl Stopper {
pub(crate) const fn new(control: Arc<Control>) -> Self {
Self { control }
}
pub fn stop(&self) {
self.control.stopping.store(true, Ordering::SeqCst);
self.control.wake.raise();
}
#[must_use]
pub fn is_stopped(&self) -> bool {
self.control.stopping.load(Ordering::SeqCst)
}
}
impl fmt::Debug for Stopper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Stopper").field("stopped", &self.is_stopped()).finish()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
pub results: u64,
pub released: Vec<EntryId>,
pub expired: u64,
pub invalid: u64,
pub abandoned: u64,
}
pub struct Worker {
config: Arc<WorkerConfig>,
streams: Arc<dyn Streams>,
handler: Arc<dyn Handler>,
clock: Clock,
control: Arc<Control>,
}
pub(crate) struct Control {
pub(crate) stopping: AtomicBool,
pub(crate) wake: Signal,
}
impl Control {
pub(crate) fn new(clock: &Clock) -> Arc<Self> {
Arc::new(Self {
stopping: AtomicBool::new(false),
wake: Signal::new(clock),
})
}
}
impl Worker {
pub fn new(config: WorkerConfig, 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) -> &WorkerConfig {
&self.config
}
pub fn spawn(self) -> Result<Running> {
let stopper = self.stopper();
let thread = thread::Builder::new()
.name("legit-streams-worker".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(Run {
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),
released: Mutex::new(Vec::new()),
lease_stop: AtomicBool::new(false),
lease_wake: Signal::new(&self.clock),
});
let lease_party = self.clock.party();
let lease_run = Arc::clone(&run);
let lease = thread::Builder::new()
.name("legit-streams-lease".to_owned())
.spawn(move || {
lease_party.bind();
lease_run.lease_loop();
})
.map_err(|error| Error::Thread(error.to_string()))?;
tracing::info!(stream = %config.stream, group = %config.group, consumer = %config.consumer, "Worker started");
run.read_loop();
run.shut_down();
run.lease_stop.store(true, Ordering::SeqCst);
run.lease_wake.raise();
if lease.join().is_err() {
tracing::error!("The lease heartbeat thread panicked");
}
run.remove_consumer();
let report = Report {
results: run.results.load(Ordering::SeqCst),
released: run.lock_released().clone(),
..Report::default()
};
tracing::info!(
results = report.results,
released = report.released.len(),
"Worker stopped"
);
Ok(report)
}
}
impl fmt::Debug for Worker {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Worker")
.field("config", &self.config)
.field("streams", &self.streams)
.field("clock", &self.clock)
.finish_non_exhaustive()
}
}
#[derive(Debug)]
pub struct Running {
stopper: Stopper,
thread: JoinHandle<Result<Report>>,
}
impl Running {
pub(crate) const fn new(stopper: Stopper, thread: JoinHandle<Result<Report>>) -> Self {
Self { stopper, thread }
}
pub fn stop(&self) {
self.stopper.stop();
}
#[must_use]
pub fn stopper(&self) -> Stopper {
self.stopper.clone()
}
#[must_use]
pub fn is_finished(&self) -> bool {
self.thread.is_finished()
}
pub fn join(self) -> Result<Report> {
self.thread.join().unwrap_or_else(|panic| panic::resume_unwind(panic))
}
}
#[derive(Default)]
pub(crate) struct Flight {
pub(crate) state: AtomicU8,
leased: AtomicBool,
lost: AtomicBool,
acking: AtomicBool,
lease: Mutex<()>,
}
pub(crate) const ACTIVE: u8 = 0;
pub(crate) const FINISHING: u8 = 1;
pub(crate) const RELEASED: u8 = 2;
impl Flight {
pub(crate) fn moves(&self, from: u8, to: u8) -> bool {
self.state
.compare_exchange(from, to, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
}
fn lock_lease(&self) -> MutexGuard<'_, ()> {
self.lease.lock().unwrap_or_else(PoisonError::into_inner)
}
}
struct Run {
config: Arc<WorkerConfig>,
streams: Arc<dyn Streams>,
handler: Arc<dyn Handler>,
clock: Clock,
control: Arc<Control>,
flights: Mutex<HashMap<EntryId, Arc<Flight>>>,
results: AtomicU64,
released: Mutex<Vec<EntryId>>,
lease_stop: AtomicBool,
lease_wake: Signal,
}
impl Run {
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 lock_released(&self) -> MutexGuard<'_, Vec<EntryId>> {
self.released.lock().unwrap_or_else(PoisonError::into_inner)
}
fn read_loop(self: &Arc<Self>) {
let config = &self.config;
let mut cursor = EntryId::ZERO;
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.xautoclaim(
&config.stream,
&config.group,
&config.consumer,
config.claim_idle,
cursor,
free,
) {
Ok(claim) => {
cursor = claim.next;
if !claim.deleted.is_empty()
&& let Err(error) = self.streams.xack_xdel(&config.stream, &config.group, &claim.deleted)
{
tracing::warn!(%error, "Couldn't acknowledge claimed entries that were deleted");
}
if !claim.claimed.is_empty() {
for entry in claim.claimed {
if self.lock_flights().contains_key(&entry.id) {
tracing::warn!(entry = %entry.id, "Claimed back an entry this worker still runs");
continue;
}
tracing::info!(entry = %entry.id, "Claimed an entry another consumer left idle");
self.dispatch(entry, true);
}
continue;
}
}
Err(error) => {
cursor = EntryId::ZERO;
tracing::warn!(%error, "Couldn't claim idle entries");
}
}
if self.stopping() {
break;
}
match self.streams.xreadgroup(
&config.stream,
&config.group,
&config.consumer,
free,
Some(config.read_block),
) {
Ok(entries) => {
for entry in entries {
if self.stopping() {
self.release(entry.id, "delivered after the stop");
} else {
self.dispatch(entry, false);
}
}
}
Err(error) => {
tracing::error!(%error, "Couldn't read 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 dispatch(self: &Arc<Self>, entry: Entry, reclaimed: bool) {
let id = entry.id;
let flight = Arc::new(Flight {
leased: AtomicBool::new(true),
..Flight::default()
});
self.lock_flights().insert(id, Arc::clone(&flight));
let run = Arc::clone(self);
let running = Arc::clone(&flight);
let spawned = thread::Builder::new()
.name("legit-streams-task".to_owned())
.spawn(move || {
run.process(&entry, reclaimed, &running);
run.remove_flight(entry.id, &running);
run.control.wake.raise();
});
if let Err(error) = spawned {
tracing::error!(entry = %id, %error, "Couldn't start a thread for a task");
self.remove_flight(id, &flight);
self.release(id, "no thread to run it on");
}
}
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, reclaimed: bool, flight: &Arc<Flight>) {
let config = &self.config;
let started = self.clock.monotonic();
let deliveries = match self.streams.xpending_entry(&config.stream, &config.group, entry.id) {
Ok(Some(pending)) => pending.deliveries,
Ok(None) => 0,
Err(error) => {
tracing::warn!(entry = %entry.id, %error, "Couldn't read the delivery count; taking it as the first");
1
}
};
if deliveries > config.max_deliveries {
let message = format!(
"delivered {deliveries} times (max {}); earlier attempts died mid-task",
config.max_deliveries
);
self.refuse(entry, flight, message, MAX_DELIVERIES_EXCEEDED, started);
return;
}
let task = match Task::from_raw(&entry.fields, &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(_)) {
UNSUPPORTED_VERSION
} else {
INVALID_TASK
};
self.refuse(entry, flight, error.to_string(), error_type, started);
return;
}
};
if flight.state.load(Ordering::SeqCst) == RELEASED {
return;
}
self.beat(entry.id, flight);
let context = Context::new(
entry.id,
deliveries,
reclaimed,
Arc::clone(flight),
Arc::clone(&self.control),
self.clock.clone(),
started,
);
tracing::debug!(task_id = task.task_id(), entry = %entry.id, deliveries, "Running a task");
let outcome = panic::catch_unwind(AssertUnwindSafe(|| self.handler.handle(&task, &context)));
if let Ok(Err(failure)) = &outcome
&& failure.is_abandon()
{
tracing::info!(
task_id = task.task_id(),
reason = failure.message(),
"The handler abandoned a task"
);
self.release_flight(entry.id, flight, "abandoned by the handler");
return;
}
if flight.lost.load(Ordering::SeqCst) {
tracing::warn!(task_id = task.task_id(), entry = %entry.id, "The task finished after its lease was lost; its result is discarded");
return;
}
let Some(result) = answer(&task, outcome) else {
return;
};
self.finish(
entry,
flight,
result,
Origin::Handler,
task.reply_to().map(str::to_owned),
started,
);
}
fn refuse(&self, entry: &Entry, flight: &Flight, message: String, error_type: &str, started: Duration) {
let Some(task_id) = answerable_task_id(&entry.fields) else {
tracing::warn!(entry = %entry.id, error_type, "The entry has no `task_id` to answer with; it's removed without a result");
self.remove(entry, flight);
return;
};
let result =
ResultBuilder::for_raw(&entry.fields, Some(task_id), Status::Error, message).error_type(error_type);
self.finish(
entry,
flight,
result,
Origin::Refusal,
fields::last(&entry.fields, "reply_to").map(str::to_owned),
started,
);
}
fn remove(&self, entry: &Entry, flight: &Flight) {
if !flight.moves(ACTIVE, FINISHING) {
return;
}
self.acknowledge(entry.id, flight, "remove an entry that isn't a task");
}
fn finish(
&self,
entry: &Entry,
flight: &Flight,
result: ResultBuilder,
origin: Origin,
reply_to: Option<String>,
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 = result_fields(&config.limits, result, origin);
let stream = match reply_to.filter(|reply_to| config.route_results_per_app && !reply_to.is_empty()) {
Some(reply_to) if is_valid_reply_to(&reply_to) => reply_to,
Some(_) => {
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");
config.result_stream.clone()
}
None => config.result_stream.clone(),
};
let pairs = fields::as_bytes(&fields);
let written = self.attempt("write the result", || {
if let Some(lost) = self.check(entry.id, flight) {
tracing::warn!(entry = %entry.id, reason = %lost, "The lease was lost before the result was written; the result is discarded");
return Ok(false);
}
self.streams.xadd(&stream, &pairs).map(|_| true)
});
if !written {
return;
}
self.results.fetch_add(1, Ordering::SeqCst);
self.acknowledge(entry.id, flight, "acknowledge the task");
}
fn acknowledge(&self, id: EntryId, flight: &Flight, what: &str) {
let config = &self.config;
let ids = [id];
let mut sent = false;
self.attempt(what, || {
let lost = if sent {
let _lease = flight.lock_lease();
if flight.lost.load(Ordering::SeqCst) {
Some(Lost::Earlier)
} else {
let lost = self.renew(id);
if lost.is_some_and(|lost| !matches!(lost, Lost::Lease(LostLease::NotPending))) {
flight.lost.store(true, Ordering::SeqCst);
}
lost
}
} else {
self.check(id, flight)
};
match lost {
Some(Lost::Lease(LostLease::NotPending)) if sent => {
return self.streams.xdel(&config.stream, &ids).map(|_| true);
}
Some(lost) => {
tracing::warn!(entry = %id, reason = %lost, "The lease was lost before the entry was acknowledged; it's left to its owner");
return Ok(false);
}
None => {}
}
flight.acking.store(true, Ordering::SeqCst);
sent = true;
self.streams.xack_xdel(&config.stream, &config.group, &ids).map(|()| true)
});
}
fn check(&self, id: EntryId, flight: &Flight) -> Option<Lost> {
let _lease = flight.lock_lease();
if flight.lost.load(Ordering::SeqCst) {
return Some(Lost::Earlier);
}
let lost = self.renew(id);
if lost.is_some() {
flight.lost.store(true, Ordering::SeqCst);
}
lost
}
fn attempt(&self, what: &str, mut step: impl FnMut() -> Result<bool>) -> bool {
let attempts = self.config.flush_attempts;
for attempt in 1..=attempts {
match step() {
Ok(done) => return done,
Err(error) if attempt == attempts => {
tracing::error!(%error, attempt, "Couldn't {what}; the task stays pending for another worker");
}
Err(error) => {
tracing::warn!(%error, attempt, "Couldn't {what}; trying again");
self.clock.sleep(self.config.flush_backoff.saturating_mul(attempt));
}
}
}
false
}
fn lease_loop(&self) {
loop {
let seen = self.lease_wake.seen();
if self.lease_stop.load(Ordering::SeqCst) {
return;
}
let leased: Vec<(EntryId, Arc<Flight>)> = self
.lock_flights()
.iter()
.filter(|(_, flight)| flight.leased.load(Ordering::SeqCst))
.map(|(id, flight)| (*id, Arc::clone(flight)))
.collect();
for (id, flight) in &leased {
self.beat(*id, flight);
}
let deadline = self.clock.monotonic().saturating_add(self.config.lease_heartbeat);
self.clock.wait(Some((&self.lease_wake, seen)), Some(deadline));
}
}
fn beat(&self, id: EntryId, flight: &Flight) {
let _lease = flight.lock_lease();
let state = flight.state.load(Ordering::SeqCst);
if flight.lost.load(Ordering::SeqCst) || state == RELEASED {
return;
}
match self.renew(id) {
Some(Lost::Lease(LostLease::NotPending)) if state == FINISHING && flight.acking.load(Ordering::SeqCst) => {}
Some(lost) => {
flight.lost.store(true, Ordering::SeqCst);
tracing::error!(entry = %id, reason = %lost, "Lost the lease on a task");
}
None => {}
}
}
fn renew(&self, id: EntryId) -> Option<Lost> {
let config = &self.config;
match self
.streams
.renew_lease(&config.stream, &config.group, &config.consumer, id)
{
Ok(Renewal::Renewed) => None,
Ok(Renewal::Lost(lost)) => Some(Lost::Lease(lost)),
Err(Error::NoGroup { .. }) => Some(Lost::NoGroup),
Err(error) => {
tracing::warn!(entry = %id, %error, "Couldn't renew a lease; trying again at the next heartbeat");
None
}
}
}
fn release_flight(&self, id: EntryId, flight: &Flight, why: &str) {
let _lease = flight.lock_lease();
if flight.moves(ACTIVE, RELEASED) {
self.release(id, why);
}
}
fn release(&self, id: EntryId, why: &str) {
let config = &self.config;
match self
.streams
.release_lease(&config.stream, &config.group, &config.consumer, id, config.claim_idle)
{
Ok(true) => tracing::info!(entry = %id, why, "Released an entry to other workers"),
Ok(false) => tracing::info!(entry = %id, why, "Didn't release an entry: it's no longer this worker's"),
Err(error) => {
tracing::warn!(entry = %id, why, %error, "Couldn't release an entry; it's claimable once idle");
}
}
self.lock_released().push(id);
}
fn shut_down(&self) {
let deadline = self.clock.monotonic().saturating_add(self.config.shutdown_grace);
loop {
let seen = self.control.wake.seen();
if self.lock_flights().is_empty() || self.clock.monotonic() >= deadline {
break;
}
self.clock.wait(Some((&self.control.wake, seen)), Some(deadline));
}
let running: Vec<(EntryId, Arc<Flight>)> = self
.lock_flights()
.iter()
.map(|(id, flight)| (*id, Arc::clone(flight)))
.collect();
for (id, flight) in running {
self.release_flight(id, &flight, "still running when the shutdown grace ran out");
}
loop {
let seen = self.control.wake.seen();
let finishing = self
.lock_flights()
.values()
.any(|flight| flight.state.load(Ordering::SeqCst) == FINISHING);
if !finishing {
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"),
}
}
}
#[derive(Debug, Clone, Copy)]
enum Lost {
Lease(LostLease),
NoGroup,
Earlier,
}
impl fmt::Display for Lost {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Lease(lost) => lost.fmt(f),
Self::NoGroup => f.write_str("the consumer group is gone"),
Self::Earlier => f.write_str("the lease was found lost earlier"),
}
}
}
pub(crate) type Outcome = std::thread::Result<std::result::Result<Reply, Failure>>;
pub(crate) fn answer(task: &Task, outcome: Outcome) -> Option<ResultBuilder> {
let result = match outcome {
Ok(Ok(reply)) => {
let mut result = TaskResult::success(task.task_id()).echo(task);
if let Some(model_name) = reply.model_name {
result = result.model_name(model_name);
}
reply
.fields
.into_iter()
.fold(result, |result, (name, value)| result.field(name, value))
}
Ok(Err(failure)) => {
let FailureKind::Error { error_type, message } = failure.kind else {
return None;
};
let mut result = TaskResult::failure(task.task_id(), message)
.echo(task)
.error_type(error_type);
if let Some(model_name) = failure.model_name {
result = result.model_name(model_name);
}
failure
.fields
.into_iter()
.fold(result, |result, (name, value)| result.field(name, value))
}
Err(panic) => {
tracing::error!(task_id = task.task_id(), "The handler panicked");
TaskResult::failure(
task.task_id(),
format!("the handler panicked: {}", panic_message(panic.as_ref())),
)
.echo(task)
.error_type(INTERNAL)
}
};
Some(result)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Origin {
Handler,
Refusal,
}
pub(crate) fn result_fields(limits: &Limits, result: ResultBuilder, origin: Origin) -> Vec<(String, String)> {
if origin == Origin::Refusal {
return refusal_fields(limits, result);
}
let fallback = result.clone();
match result.build_within(limits) {
Ok(result) => return result.into_fields(),
Err(Error::TooLarge { .. }) if fallback.is_error() => return refusal_fields(limits, fallback),
Err(Error::TooLarge { what, limit, actual }) => {
let message = format!("the result's {what} is {actual}, over the limit of {limit}");
let error = fallback.into_error(message, RESULT_TOO_LARGE);
let fields = error.clone().into_fields();
if limits.check(&fields).is_ok() {
return fields;
}
return error.bare().into_fields();
}
Err(Error::MissingField(_) | Error::EmptyField(_)) => {}
Err(error) => {
let message = format!("the handler's reply isn't a valid result: {error}");
let error = fallback.into_error(message, INTERNAL);
if let Ok(result) = error.clone().build_within(limits) {
return result.into_fields();
}
return error.bare().into_fields();
}
}
let fields = fallback.clone().into_fields();
if fields::check_strings(&fields, limits).is_ok() {
fields
} else {
fallback.bare().into_fields()
}
}
fn refusal_fields(limits: &Limits, result: ResultBuilder) -> Vec<(String, String)> {
let steps = [
result.clone(),
result.clone().without_echoes(),
result.clone().cut(1024, usize::MAX),
result.clone().cut(0, usize::MAX),
];
for step in steps {
let fields = step.into_fields();
if fields::check_strings(&fields, limits).is_ok() {
return fields;
}
}
result.cut(0, 0).into_fields()
}
fn panic_message(panic: &(dyn std::any::Any + Send)) -> &str {
panic
.downcast_ref::<&str>()
.copied()
.or_else(|| panic.downcast_ref::<String>().map(String::as_str))
.unwrap_or("a panic without a message")
}