|
| 1 | +use async_priority_channel as mpsc; |
| 2 | +use tokio::sync::oneshot; |
| 3 | + |
| 4 | +use super::traits::Job; |
| 5 | +use super::traits::JobResult; |
| 6 | + |
| 7 | +// todo: fix it so that jobs with same priority execute FIFO. |
| 8 | +/// implements a prioritized job queue that sends result of each job to a listener. |
| 9 | +/// At present order of jobs with the same priority is undefined. |
| 10 | +type JobResultOneShotChannel = oneshot::Sender<Box<dyn JobResult>>; |
| 11 | + |
| 12 | +pub struct JobQueue<P: Ord> { |
| 13 | + tx: mpsc::Sender<(Box<dyn Job>, JobResultOneShotChannel), P>, |
| 14 | +} |
| 15 | + |
| 16 | +impl<P: Ord> std::fmt::Debug for JobQueue<P> { |
| 17 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 18 | + f.debug_struct("JobQueue") |
| 19 | + .field("tx", &"mpsc::Sender") |
| 20 | + .finish() |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +impl<P: Ord> Clone for JobQueue<P> { |
| 25 | + fn clone(&self) -> Self { |
| 26 | + Self { |
| 27 | + tx: self.tx.clone(), |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl<P: Ord + Send + Sync + 'static> JobQueue<P> { |
| 33 | + // creates job queue and starts it processing. returns immediately. |
| 34 | + pub fn start() -> Self { |
| 35 | + let (tx, rx) = mpsc::unbounded::<(Box<dyn Job>, JobResultOneShotChannel), P>(); |
| 36 | + |
| 37 | + // spawns background task that processes job-queue and runs jobs. |
| 38 | + tokio::spawn(async move { |
| 39 | + while let Ok(r) = rx.recv().await { |
| 40 | + let (job, otx) = r.0; |
| 41 | + |
| 42 | + let result = match job.is_async() { |
| 43 | + true => job.run_async().await, |
| 44 | + false => tokio::task::spawn_blocking(move || job.run()) |
| 45 | + .await |
| 46 | + .unwrap(), |
| 47 | + }; |
| 48 | + let _ = otx.send(result); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + Self { tx } |
| 53 | + } |
| 54 | + |
| 55 | + // alias of Self::start(). |
| 56 | + // here for two reasons: |
| 57 | + // 1. backwards compat with existing tests |
| 58 | + // 2. if tests call dummy() instead of start(), then it is easier |
| 59 | + // to find where start() is called for real. |
| 60 | + #[cfg(test)] |
| 61 | + pub fn dummy() -> Self { |
| 62 | + Self::start() |
| 63 | + } |
| 64 | + |
| 65 | + // adds job to job-queue and returns immediately. |
| 66 | + pub async fn add_job( |
| 67 | + &self, |
| 68 | + job: Box<dyn Job>, |
| 69 | + priority: P, |
| 70 | + ) -> anyhow::Result<oneshot::Receiver<Box<dyn JobResult>>> { |
| 71 | + let (otx, orx) = oneshot::channel(); |
| 72 | + self.tx.send((job, otx), priority).await?; |
| 73 | + Ok(orx) |
| 74 | + } |
| 75 | + |
| 76 | + // adds job to job-queue, waits for job completion, and returns job result. |
| 77 | + pub async fn add_and_await_job( |
| 78 | + &self, |
| 79 | + job: Box<dyn Job>, |
| 80 | + priority: P, |
| 81 | + ) -> anyhow::Result<Box<dyn JobResult>> { |
| 82 | + let (otx, orx) = oneshot::channel(); |
| 83 | + self.tx.send((job, otx), priority).await?; |
| 84 | + Ok(orx.await?) |
| 85 | + } |
| 86 | + |
| 87 | + #[cfg(test)] |
| 88 | + pub async fn wait_until_queue_empty(&self) { |
| 89 | + loop { |
| 90 | + if self.tx.is_empty() { |
| 91 | + break; |
| 92 | + } |
| 93 | + tokio::time::sleep(std::time::Duration::from_millis(10)).await; |
| 94 | + } |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +#[cfg(test)] |
| 99 | +mod tests { |
| 100 | + use std::any::Any; |
| 101 | + |
| 102 | + use super::*; |
| 103 | + |
| 104 | + #[derive(PartialEq, Debug)] |
| 105 | + struct DoubleJobResult(u64, u64); |
| 106 | + impl JobResult for DoubleJobResult { |
| 107 | + fn as_any(&self) -> &dyn Any { |
| 108 | + self |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + // a job that doubles the input value. implements Job. |
| 113 | + struct DoubleJob { |
| 114 | + data: u64, |
| 115 | + } |
| 116 | + |
| 117 | + impl Job for DoubleJob { |
| 118 | + fn is_async(&self) -> bool { |
| 119 | + false |
| 120 | + } |
| 121 | + |
| 122 | + fn run(&self) -> Box<dyn JobResult> { |
| 123 | + let r = DoubleJobResult(self.data, self.data * 2); |
| 124 | + |
| 125 | + println!("{} * 2 = {}", r.0, r.1); |
| 126 | + Box::new(r) |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + // todo: make test(s) for async jobs. |
| 131 | + |
| 132 | + /// todo: this should verify the priority order of jobs. |
| 133 | + /// presently each job just prints result and |
| 134 | + /// human can manually verify output. |
| 135 | + #[tokio::test] |
| 136 | + async fn run_jobs_by_priority() -> anyhow::Result<()> { |
| 137 | + // create a job queue |
| 138 | + let job_queue = JobQueue::<u8>::start(); |
| 139 | + |
| 140 | + // create 10 jobs |
| 141 | + for i in 0..10 { |
| 142 | + let job1 = Box::new(DoubleJob { data: i }); |
| 143 | + let job2 = Box::new(DoubleJob { data: i * 100 }); |
| 144 | + let job3 = Box::new(DoubleJob { data: i * 1000 }); |
| 145 | + |
| 146 | + // process job and print results. |
| 147 | + job_queue.add_job(job1, 1).await?; |
| 148 | + job_queue.add_job(job2, 2).await?; |
| 149 | + job_queue.add_job(job3, 3).await?; |
| 150 | + } |
| 151 | + |
| 152 | + job_queue.wait_until_queue_empty().await; |
| 153 | + |
| 154 | + Ok(()) |
| 155 | + } |
| 156 | + |
| 157 | + #[tokio::test] |
| 158 | + async fn get_result() -> anyhow::Result<()> { |
| 159 | + // create a job queue |
| 160 | + let job_queue = JobQueue::<u8>::start(); |
| 161 | + |
| 162 | + // create 10 jobs |
| 163 | + for i in 0..10 { |
| 164 | + let job = Box::new(DoubleJob { data: i }); |
| 165 | + |
| 166 | + let result = job_queue.add_and_await_job(job, 1).await?; |
| 167 | + assert_eq!( |
| 168 | + Some(&DoubleJobResult(i, i * 2)), |
| 169 | + result.as_any().downcast_ref::<DoubleJobResult>() |
| 170 | + ); |
| 171 | + } |
| 172 | + |
| 173 | + Ok(()) |
| 174 | + } |
| 175 | +} |
0 commit comments