summaryrefslogtreecommitdiffstats
path: root/src/launcher/download.rs
blob: 5240d552cd964617db7eccc4fab721c8b1cc727d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use std::cmp::min;
use std::collections::VecDeque;
use std::error::Error;
use std::future::Future;
use std::pin::{pin, Pin};
use std::task::{Context, Poll};
use curl::easy::{Easy2, Handler, WriteError};
use curl::multi::{Easy2Handle, EasyHandle, Multi};
use tokio::task::spawn_blocking;
use crate::launcher::constants::USER_AGENT;

trait Download {
    async fn prepare(&mut self, easy: &EasyHandle) -> Result<bool, Box<dyn Error>>;
    async fn handle_chunk(&mut self, data: &[u8]) -> Result<(), Box<dyn Error>>;
    async fn finish(&mut self) -> Result<(), Box<dyn Error>>;
}

#[derive(Clone, Copy)]
enum MultiDownloaderState {
    Primed,
    Running,
    Complete
}

struct MultiDownloader<T>
where
    T: Download + Send + Unpin + 'static
{
    state: MultiDownloaderState,
    nhandles: usize,
    jobs: Option<VecDeque<T>>
}

impl<T> MultiDownloader<T>
where
    T: Download + Send + Unpin + 'static
{
    // TODO: this interface is kind of weird (we have to take ownership of the jobs, but maybe this isn't the best way to do that)

    pub fn new(jobs: Vec<T>, nhandles: usize) -> MultiDownloader<T> {
        assert!(nhandles > 0);

        MultiDownloader {
            state: MultiDownloaderState::Primed,
            nhandles,
            jobs: Some(jobs.into())
        }
    }
}

struct MultiDownloadResult {

}

impl<T> Future for MultiDownloader<T>
where
    T: Download + Send + Unpin + 'static
{
    type Output = MultiDownloadResult;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let self_mut = self.get_mut();
        match self_mut.state {
            MultiDownloaderState::Primed => {
                self_mut.state = MultiDownloaderState::Running;
                let jobs = self_mut.jobs.take().unwrap();
                let nhandles = self_mut.nhandles;

                spawn_blocking(move || {
                    // TODO
                    MultiDownloadBlocking::new(jobs, nhandles).perform();
                });

                Poll::Pending
            },
            MultiDownloaderState::Running => {
                Poll::Pending // TODO
            },
            MultiDownloaderState::Complete => panic!("multi download polled after completion")
        }
    }
}

struct MultiHandler<T: Download> {
    job: Option<T>
}

impl<T: Download> Handler for MultiHandler<T> {
    fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
        todo!()
    }
}

struct MultiDownloadBlocking<T: Download> {
    multi: Multi,
    easy_handles: Vec<Easy2Handle<MultiHandler<T>>>,
    jobs: VecDeque<T>
}

impl<'a, T: Download> MultiDownloadBlocking<T> {
    fn new(jobs: VecDeque<T>, nhandles: usize) -> MultiDownloadBlocking<T> {
        assert!(nhandles > 0);

        let nhandles = min(nhandles, jobs.len());

        let multi = Multi::new();
        let mut easy_handles = Vec::with_capacity(nhandles);

        for n in 0..nhandles {
            let mut easy = Easy2::new(MultiHandler { job: None });
            easy.useragent(USER_AGENT).expect("setting user agent shouldn't fail");

            let mut handle = multi.add2(easy).expect("adding easy handle cannot fail");
            handle.set_token(n).expect("setting token cannot fail");
            easy_handles.push(handle);
        }

        MultiDownloadBlocking {
            multi,
            easy_handles,
            jobs
        }
    }
    
    fn prepare_job(&mut self, easy: &mut Easy2Handle<MultiHandler<T>>, job: T) {
        let handler = easy.get_mut();

        todo!()
    }

    fn perform(&mut self) -> MultiDownloadResult {
        todo!()
    }
}

// 
// pub struct MultiDownloader<'j> {
//     state: MultiDownloaderState,
//     jobs: VecDeque<DownloadJob>,
//     multi: Multi,
//     handles: Vec<Easy2Handle<EasyHandler<'j>>>
// }
// 
// pub struct EasyHandler<'j> {
//     job: Option<&'j DownloadJob>
// }
// 
// impl<'j> Handler for EasyHandler<'j> {
//     fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
// 
//     }
// }
// 
// impl<'j, 'js, T> MultiDownloader<'j, 'js, T>
// where
//     T: Download + Sync + Send + ?Sized
// {
//     pub fn new(jobs: &'js [&'j T]) -> MultiDownloader<'j, 'js, T> {
//         Self::with_handles(jobs, 8)
//     }
// 
//     pub fn with_handles(jobs: &'js [&'j T], nhandles: usize) -> MultiDownloader<'j, 'js, T> {
//         assert!(nhandles > 0);
// 
//         let mut handles = Vec::with_capacity(nhandles);
//         let multi = Multi::new();
// 
//         for n in 0..nhandles {
//             let mut easy = multi.add2(Easy2::new(EasyHandler { job: None })).expect("adding easy handle should not fail");
//             easy.set_token(n).expect("setting token should not fail");
// 
//             handles.push(easy);
//         }
// 
//         MultiDownloader {
//             state: MultiDownloaderState::Primed,
//             
//             multi,
//             handles
//         }
//     }
// 
//     fn next_job(&mut self) -> Option<&T> {
//         let oj = self.jobs.get(self.job_idx).cloned();
//         self.job_idx += 1;
//         oj
//     }
// }
// 
// pub struct MultiDownloadResult {
// 
// }
// 
// impl<'j, 'js, T> Future for MultiDownloader<'j, 'js, T>
// where
//     T: Download + Sync + Send + ?Sized
// {
//     type Output = MultiDownloadResult;
// 
//     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
//         let self_mut = self.get_mut();
//         match self_mut.state {
//             MultiDownloaderState::Primed => {
//                 self_mut.state = MultiDownloaderState::Running;
// 
//                 // TODO: assign download jobs to each
// 
//                 Poll::Pending
//             },
//             MultiDownloaderState::Running => {
//                 todo!()
//             },
//             MultiDownloaderState::Complete => panic!("multi downloader polled after completion")
//         }
//     }
// }

// fn sample() {
//     struct AbcdDownloader {
//         file: Option<File>,
//         path: PathBuf,
//         url: String,
//         expect_size: usize,
//         expect_sha1: Digest
//     }
//
//     impl Download for AbcdDownloader {
//         async fn before_download(&mut self) -> Result<bool, Box<dyn Error>> {
//             let mut file = match File::open(&self.path).await {
//                 Ok(f) => f,
//                 Err(e) => return match e.kind() {
//                     ErrorKind::NotFound => {
//                         // TODO: ensure parent dirs exist
//
//                         Ok(true)
//                     },
//                     _ => Err(e.into())
//                 }
//             };
//
//             let mut buf = [0u8; 4096];
//             let mut sha1 = Sha1::new();
//             let mut tally = 0usize;
//
//             loop {
//                 let n = file.read(&mut buf[..]).await?;
//                 if n == 0 {
//                     file.seek(SeekFrom::Start(0)).await?;
//                     break;
//                 }
//
//                 sha1.update(&buf[..n]);
//                 tally += n;
//             }
//
//             Ok(tally != self.expect_size || sha1.digest() != self.expect_sha1)
//         }
//
//         async fn handle_chunk(&mut self, data: &[u8]) -> Result<usize, WriteError> {
//             self.file.unwrap().write_all(data).await
//         }
//
//         async fn after_download(&mut self) -> Result<(), Box<dyn Error>> {
//             todo!()
//         }
//     }
//
//     let mut jobs = Vec::new();
//     jobs.push(AbcdDownloader {
//         file: None,
//         path: PathBuf::from("/home/bigfoot/test.words"),
//         url: String::from("https://github.com/"),
//         expect_size: 10,
//         expect_sha1: Digest::default()
//     });
//
//     let abcd = MultiDownloader::new(jobs.iter().map(|a| a).collect::<Vec<&AbcdDownloader>>().as_slice());
// }