Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle only the latest waker #481

Merged
merged 2 commits into from
Dec 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 24 additions & 9 deletions packages/apalis-core/src/worker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ impl<S, P> Worker<Ready<S, P>> {
let ctx = Context {
running: Arc::default(),
task_count: Arc::default(),
wakers: Arc::default(),
waker: Arc::default(),
shutdown: self.state.shutdown,
event_handler: self.state.event_handler.clone(),
is_ready: Arc::default(),
Expand Down Expand Up @@ -400,7 +400,7 @@ impl Future for Runnable {
#[derive(Clone, Default)]
pub struct Context {
task_count: Arc<AtomicUsize>,
wakers: Arc<Mutex<Vec<Waker>>>,
waker: Arc<Mutex<Option<Waker>>>,
running: Arc<AtomicBool>,
shutdown: Option<Shutdown>,
event_handler: EventHandler,
Expand Down Expand Up @@ -469,9 +469,9 @@ impl Context {
}

pub(crate) fn wake(&self) {
if let Ok(mut wakers) = self.wakers.lock() {
for waker in wakers.drain(..) {
waker.wake();
if let Ok(waker) = self.waker.lock() {
if let Some(waker) = &*waker {
waker.wake_by_ref();
}
}
}
Expand Down Expand Up @@ -501,13 +501,26 @@ impl Context {
}

fn add_waker(&self, cx: &mut TaskCtx<'_>) {
if let Ok(mut wakers) = self.wakers.lock() {
if !wakers.iter().any(|w| w.will_wake(cx.waker())) {
wakers.push(cx.waker().clone());
if let Ok(mut waker_guard) = self.waker.lock() {
if waker_guard
.as_ref()
.map_or(true, |stored_waker| !stored_waker.will_wake(cx.waker()))
{
*waker_guard = Some(cx.waker().clone());
}
}
}

/// Checks if the stored waker matches the current one.
fn has_recent_waker(&self, cx: &TaskCtx<'_>) -> bool {
if let Ok(waker_guard) = self.waker.lock() {
if let Some(stored_waker) = &*waker_guard {
return stored_waker.will_wake(cx.waker());
}
}
false
}

/// Returns if the worker is ready to consume new tasks
pub fn is_ready(&self) -> bool {
self.is_ready.load(Ordering::Acquire) && !self.is_shutting_down()
Expand All @@ -522,7 +535,9 @@ impl Future for Context {
if self.is_shutting_down() && task_count == 0 {
Poll::Ready(())
} else {
self.add_waker(cx);
if !self.has_recent_waker(cx) {
self.add_waker(cx);
}
Poll::Pending
}
}
Expand Down
Loading