@@ -6,6 +6,7 @@ use tokio::{
6
6
io:: AsyncWriteExt ,
7
7
sync:: { mpsc, oneshot, watch, Semaphore } ,
8
8
} ;
9
+ use tokio_util:: sync:: CancellationToken ;
9
10
10
11
const QUEUE_SIZE : usize = 100 ;
11
12
const MAX_RETRIES : usize = 3 ;
@@ -16,7 +17,7 @@ struct DownloadRequest {
16
17
destination : PathBuf ,
17
18
result : oneshot:: Sender < Result < File , Error > > ,
18
19
status : watch:: Sender < Status > ,
19
- cancel : oneshot :: Receiver < ( ) > ,
20
+ cancel : CancellationToken ,
20
21
}
21
22
22
23
#[ derive( Debug , Clone , Copy , PartialEq , Eq ) ]
@@ -29,7 +30,7 @@ pub struct DownloadProgress {
29
30
pub struct DownloadHandle {
30
31
result : oneshot:: Receiver < Result < File , Error > > ,
31
32
status : watch:: Receiver < Status > ,
32
- cancel : oneshot :: Sender < ( ) > ,
33
+ cancel : CancellationToken ,
33
34
}
34
35
35
36
impl std:: future:: Future for DownloadHandle {
@@ -58,8 +59,8 @@ impl DownloadHandle {
58
59
self . status . changed ( ) . await
59
60
}
60
61
61
- pub fn cancel ( self ) {
62
- self . cancel . send ( ( ) ) . ok ( ) ;
62
+ pub fn cancel ( & self ) {
63
+ self . cancel . cancel ( ) ;
63
64
}
64
65
}
65
66
@@ -114,22 +115,22 @@ impl DownloadManager {
114
115
pub fn add_request ( & self , url : Url , destination : PathBuf ) -> DownloadHandle {
115
116
let ( result_tx, result_rx) = oneshot:: channel ( ) ;
116
117
let ( status_tx, status_rx) = watch:: channel ( Status :: Pending ) ;
117
- let ( cancel_tx , cancel_rx ) = oneshot :: channel ( ) ;
118
+ let cancel = CancellationToken :: new ( ) ;
118
119
119
120
let req = DownloadRequest {
120
121
url,
121
122
destination,
122
123
result : result_tx,
123
124
status : status_tx,
124
- cancel : cancel_rx ,
125
+ cancel : cancel . clone ( ) ,
125
126
} ;
126
127
127
128
let _ = self . queue . try_send ( req) ;
128
129
129
130
DownloadHandle {
130
131
result : result_rx,
131
132
status : status_rx,
132
- cancel : cancel_tx ,
133
+ cancel,
133
134
}
134
135
}
135
136
}
@@ -193,7 +194,7 @@ async fn download_thread(client: Client, mut req: DownloadRequest) {
193
194
194
195
tokio:: select! {
195
196
_ = tokio:: time:: sleep( delay) => { } ,
196
- _ = & mut req. cancel => {
197
+ _ = req. cancel. cancelled ( ) => {
197
198
req. status. send( Status :: Failed ) . ok( ) ;
198
199
req. result. send( Err ( Error :: Download ( DownloadError :: Cancelled ) ) ) . ok( ) ;
199
200
return ;
@@ -247,7 +248,7 @@ async fn download(client: Client, req: &mut DownloadRequest) -> Result<File, Err
247
248
update_progress ( bytes_downloaded, total_bytes) ;
248
249
loop {
249
250
tokio:: select! {
250
- _ = & mut req. cancel => {
251
+ _ = req. cancel. cancelled ( ) => {
251
252
drop( file) ; // Manually drop the file handle to ensure that deletion doesn't fail
252
253
tokio:: fs:: remove_file( & req. destination) . await ?;
253
254
return Err ( Error :: Download ( DownloadError :: Cancelled ) ) ;
0 commit comments