-
Notifications
You must be signed in to change notification settings - Fork 66
A0-1795: add task queue #836
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
fbce119
add task queue
maciejnems 8af670f
add duration check
maciejnems c5d7812
hmmmm
maciejnems 897c9c2
remove PeekMut
maciejnems c3f1bf9
Merge remote-tracking branch 'origin' into A0-1795-task-queue
maciejnems ee22298
Merge remote-tracking branch 'origin' into A0-1795-task-queue
maciejnems 6160950
extract aleph-block-sync LOG_TARGET
maciejnems 574bbb5
remove require PartialEq and Eq implementation
maciejnems 2a2ea45
increase to 50
maciejnems 8adde72
hmmmmmm
maciejnems bcadb09
Merge branch 'main' into A0-1795-task-queue
maciejnems File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| use std::{ | ||
| cmp::Ordering, | ||
| collections::BinaryHeap, | ||
| fmt::{Debug, Formatter}, | ||
| }; | ||
|
|
||
| use log::warn; | ||
| use tokio::time::{sleep, Duration, Instant}; | ||
|
|
||
| use crate::sync::LOG_TARGET; | ||
|
|
||
| #[derive(Clone)] | ||
| struct ScheduledTask<T> { | ||
| task: T, | ||
| scheduled_time: Instant, | ||
| } | ||
|
|
||
| impl<T> Eq for ScheduledTask<T> {} | ||
|
|
||
| impl<T> PartialEq for ScheduledTask<T> { | ||
| fn eq(&self, other: &Self) -> bool { | ||
| other.scheduled_time.eq(&self.scheduled_time) | ||
| } | ||
| } | ||
|
|
||
| impl<T> PartialOrd for ScheduledTask<T> { | ||
| fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | ||
| Some(self.cmp(other)) | ||
| } | ||
| } | ||
|
|
||
| impl<T> Ord for ScheduledTask<T> { | ||
| /// Compare tasks so that earlier times come first in a max-heap. | ||
| fn cmp(&self, other: &Self) -> Ordering { | ||
| other.scheduled_time.cmp(&self.scheduled_time) | ||
| } | ||
| } | ||
|
|
||
| #[derive(Clone, Default)] | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I wouldn't derive |
||
| pub struct TaskQueue<T> { | ||
| queue: BinaryHeap<ScheduledTask<T>>, | ||
| } | ||
|
|
||
| impl<T> Debug for TaskQueue<T> { | ||
| fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
| f.debug_struct("TaskQueue") | ||
| .field("task count", &self.queue.len()) | ||
| .finish() | ||
| } | ||
| } | ||
|
|
||
| /// Implements a queue allowing for scheduling tasks for some time in the future. | ||
| /// | ||
| /// Does not actually execute any tasks, is used for ordering in time only. | ||
| impl<T> TaskQueue<T> { | ||
| /// Creates an empty queue. | ||
| pub fn new() -> Self { | ||
| Self { | ||
| queue: BinaryHeap::new(), | ||
| } | ||
| } | ||
|
|
||
| /// Schedules `task` for after `delay`. | ||
| pub fn schedule_in(&mut self, task: T, delay: Duration) { | ||
| let scheduled_time = match Instant::now().checked_add(delay) { | ||
fixxxedpoint marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| Some(time) => time, | ||
| None => { | ||
| warn!( | ||
| target: LOG_TARGET, | ||
| "Could not schedule task in {:?}. Instant out of bound.", delay | ||
| ); | ||
| return; | ||
| } | ||
| }; | ||
| self.queue.push(ScheduledTask { | ||
| task, | ||
| scheduled_time, | ||
| }); | ||
| } | ||
|
|
||
| /// Awaits for the first and most overdue task and returns it. Returns `None` if there are no tasks. | ||
| pub async fn pop(&mut self) -> Option<T> { | ||
| let scheduled_task = self.queue.peek()?; | ||
|
|
||
| let duration = scheduled_task | ||
| .scheduled_time | ||
| .saturating_duration_since(Instant::now()); | ||
| if !duration.is_zero() { | ||
| sleep(duration).await; | ||
| } | ||
| self.queue.pop().map(|t| t.task) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use tokio::time::{timeout, Duration}; | ||
|
|
||
| use super::TaskQueue; | ||
|
|
||
| #[tokio::test] | ||
| async fn test_scheduling() { | ||
| let mut q = TaskQueue::new(); | ||
| q.schedule_in(2, Duration::from_millis(50)); | ||
| q.schedule_in(1, Duration::from_millis(20)); | ||
|
|
||
| assert!(timeout(Duration::from_millis(5), q.pop()).await.is_err()); | ||
fixxxedpoint marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| assert_eq!( | ||
| timeout(Duration::from_millis(20), q.pop()).await, | ||
| Ok(Some(1)) | ||
| ); | ||
| assert!(timeout(Duration::from_millis(10), q.pop()).await.is_err()); | ||
| assert_eq!( | ||
| timeout(Duration::from_millis(50), q.pop()).await, | ||
| Ok(Some(2)) | ||
| ); | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.