|
| 1 | +use super::Status; |
| 2 | +use crate::Error; |
| 3 | +use tokio::{ |
| 4 | + fs::File, |
| 5 | + sync::{oneshot, watch}, |
| 6 | +}; |
| 7 | +use tokio_util::sync::CancellationToken; |
| 8 | + |
| 9 | +#[derive(Debug)] |
| 10 | +pub struct DownloadHandle { |
| 11 | + result: oneshot::Receiver<Result<File, Error>>, |
| 12 | + status: watch::Receiver<Status>, |
| 13 | + cancel: CancellationToken, |
| 14 | +} |
| 15 | + |
| 16 | +impl DownloadHandle { |
| 17 | + pub fn new( |
| 18 | + result: oneshot::Receiver<Result<File, Error>>, |
| 19 | + status: watch::Receiver<Status>, |
| 20 | + cancel: CancellationToken, |
| 21 | + ) -> Self { |
| 22 | + Self { |
| 23 | + result, |
| 24 | + status, |
| 25 | + cancel, |
| 26 | + } |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +impl std::future::Future for DownloadHandle { |
| 31 | + type Output = Result<tokio::fs::File, Error>; |
| 32 | + |
| 33 | + fn poll( |
| 34 | + mut self: std::pin::Pin<&mut Self>, |
| 35 | + cx: &mut std::task::Context<'_>, |
| 36 | + ) -> std::task::Poll<Self::Output> { |
| 37 | + use std::pin::Pin; |
| 38 | + use std::task::Poll; |
| 39 | + match Pin::new(&mut self.result).poll(cx) { |
| 40 | + Poll::Ready(Ok(result)) => Poll::Ready(result), |
| 41 | + Poll::Ready(Err(e)) => Poll::Ready(Err(Error::Oneshot(e))), |
| 42 | + Poll::Pending => Poll::Pending, |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl DownloadHandle { |
| 48 | + pub fn status(&self) -> Status { |
| 49 | + *self.status.borrow() |
| 50 | + } |
| 51 | + |
| 52 | + pub async fn wait_for_status_update(&mut self) -> Result<(), watch::error::RecvError> { |
| 53 | + self.status.changed().await |
| 54 | + } |
| 55 | + |
| 56 | + pub fn cancel(&self) { |
| 57 | + self.cancel.cancel(); |
| 58 | + } |
| 59 | +} |
0 commit comments