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
|
use isahc::prelude::*;
use isahc::{config::RedirectPolicy, HttpClient, Request};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use thiserror::Error;
use tokio::{io::AsyncWriteExt as _, sync::Mutex};
use tokio_stream::StreamExt as _;
use tokio_util::compat::FuturesAsyncReadCompatExt as _;
use tokio_util::io::ReaderStream;
use url::Url;
const STREAM_BUFFER_SIZE_BYTES: usize = 65535;
#[derive(Error, Debug)]
pub enum DownloaderError {
#[error("RequestError: {0}")]
Request(#[from] isahc::Error),
#[error("HttpError: {0}")]
HttpError(#[from] isahc::http::Error),
#[error("IoError: {0}")]
Io(#[source] std::io::Error),
#[error("StdIoError: {0}")]
StdIoError(#[from] std::io::Error),
#[error("File name cannot be found in URL: {0}")]
NotFoundFileName(String),
#[error("Failed to parse URL body: {0}")]
InvalidUrlBody(String),
}
#[derive(Debug, Clone)]
pub struct Downloader {
client: Option<HttpClient>,
location: PathBuf,
// the whole thing is an Arc/Mutex so that Downloader is thread safe, and the individual values of
// the HashMap are Arc/Mutexes (Mutexi?) to represent that individual downloads should not
// happen concurrently
download_locks: Arc<Mutex<HashMap<String, Arc<Mutex<()>>>>>,
}
impl Default for Downloader {
fn default() -> Self {
Self {
client: HttpClient::builder()
// TODO: timeout?
.redirect_policy(RedirectPolicy::Follow)
.build()
.ok(),
location: PathBuf::from(""),
download_locks: Default::default(),
}
}
}
impl Downloader {
pub fn new(location: PathBuf) -> Self {
Self {
client: HttpClient::builder()
// TODO: timeout?
.redirect_policy(RedirectPolicy::Follow)
.build()
.ok(),
location,
download_locks: Default::default(),
}
}
pub async fn download(
&self,
url: &str,
file_name: Option<&str>,
) -> Result<(), DownloaderError> {
let Some(client) = &self.client else {
log::error!("No Http client found, cannot perform requests - this is likely a misconfiguration of isahc::HttpClient");
return Ok(());
};
let file_name = match file_name {
Some(name) => name.to_string(),
None => self.parse_name(url)?,
};
// we do this to make sure only one download of a specific url is happening at a time
// otherwise the downloads corrupt each other (and we waste lots of system resources)
let download_lock = self.acquire_download_lock(&file_name).await;
// it's important that _lock remains in scope, otherwise it gets dropped and the lock is
// released before the download is complete
let _lock = download_lock.lock().await;
let file_path = self.location.join(file_name.as_str());
if file_path.exists() {
log::debug!("File already exists: {:?}", file_path);
return Ok(());
}
let file_part_path = self.location.join(format!("{}.part", file_name));
let (mut target, file_part_size) = {
if file_part_path.exists() {
let file_part = tokio::fs::OpenOptions::new()
.append(true)
.write(true)
.open(&file_part_path)
.await
.map_err(|e| DownloaderError::Io(e))?;
let file_part_size = file_part
.metadata()
.await
.map_err(|e| DownloaderError::Io(e))?
.len();
log::debug!("Resuming download from {} bytes", file_part_size);
(file_part, file_part_size)
} else {
let file_part = tokio::fs::File::create(&file_part_path)
.await
.map_err(|e| DownloaderError::Io(e))?;
(file_part, 0)
}
};
let request = Request::get(url)
.header("Content-Type", "application/octet-stream")
.header("Range", format!("bytes={}-", file_part_size))
.body(())?;
let mut res = client.send_async(request).await?;
let body = res.body_mut();
let mut stream = ReaderStream::with_capacity(body.compat(), STREAM_BUFFER_SIZE_BYTES);
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(DownloaderError::Io)?;
target
.write_all(&chunk)
.await
.map_err(DownloaderError::Io)?;
}
log::debug!("Download complete: {:?}", file_part_path);
tokio::fs::rename(file_part_path, file_path)
.await
.map_err(|e| DownloaderError::Io(e))?;
Ok(())
}
pub async fn download_without_cache(url: &str) -> Result<String, DownloaderError> {
let request = Request::get(url)
.header("Content-Type", "application/octet-stream")
.body(())?;
let client = HttpClient::builder()
// TODO: timeout?
.redirect_policy(RedirectPolicy::Follow)
.build()?;
let mut res = client.send_async(request).await?;
let mut downloaded_bytes: Vec<u8> = vec![];
let body = res.body_mut();
let mut stream = ReaderStream::with_capacity(body.compat(), STREAM_BUFFER_SIZE_BYTES);
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(DownloaderError::Io)?;
downloaded_bytes.extend_from_slice(&*chunk);
}
log::debug!("Download complete");
let stringified = String::from_utf8(downloaded_bytes)
.map_err(|e| DownloaderError::InvalidUrlBody(format!("{}", e)))?;
Ok(stringified)
}
/// Download the content of a URL and block for the result.
///
/// Wraps the `async` call to [`download_without_cache`] such that it can be used from sync
/// code. This is achieved by either:
///
/// 1. Reusing an existing async runtime in case one is present in the current thread, or
/// 2. Spawning a new async runtime on the current thread
///
/// If neither of these works, an error is returned instead.
///
/// # Note
///
/// At the moment, this function is only here to bridge the gap between the async
/// [`Downloader`] impl and the sync [`Layout`] code that ultimately calls this function. This
/// is needed since the Layout code can't trivially be turned `async` without a lot of
/// refactoring, while the Downloader is used in many other places with async code and can't
/// sensibly be sync. Maybe in the future, when more code around here is async, we can drop
/// this function.
pub fn download_without_cache_blocking(url: &str) -> Result<String, DownloaderError> {
let runtime_handle = match tokio::runtime::Handle::try_current() {
Ok(handle) => handle.clone(),
Err(e) if e.is_missing_context() => {
let runtime = tokio::runtime::Builder::new_current_thread()
.thread_name("ephemeral runtime for downloader implementation")
.build()
.map_err(DownloaderError::Io)?;
runtime.handle().clone()
},
_ => {
return Err(DownloaderError::Io(std::io::Error::new(
std::io::ErrorKind::Other,
"failed to spawn runtime for download task",
)))
},
};
runtime_handle.block_on(async move { Downloader::download_without_cache(url).await })
}
fn parse_name(&self, url: &str) -> Result<String, DownloaderError> {
Url::parse(url)
.map_err(|_| DownloaderError::NotFoundFileName(url.to_string()))?
.path_segments()
.ok_or_else(|| DownloaderError::NotFoundFileName(url.to_string()))?
.last()
.ok_or_else(|| DownloaderError::NotFoundFileName(url.to_string()))
.map(|s| s.to_string())
}
async fn acquire_download_lock(&self, file_name: &String) -> Arc<Mutex<()>> {
let mut lock_dict = self.download_locks.lock().await;
let download_lock = lock_dict
.entry(file_name.clone())
.or_insert_with(|| Default::default());
download_lock.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[ignore]
#[tokio::test]
async fn test_download_ok() {
let location = tempdir().expect("Failed to create temp directory");
let location_path = location.path();
let downloader = Downloader::new(location_path.to_path_buf());
let result = downloader
.download(
"https://github.com/imsnif/monocle/releases/download/0.39.0/monocle.wasm",
Some("monocle.wasm"),
)
.await
.is_ok();
assert!(result);
assert!(location_path.join("monocle.wasm").exists());
location.close().expect("Failed to close temp directory");
}
#[ignore]
#[tokio::test]
async fn test_download_without_file_name() {
let location = tempdir().expect("Failed to create temp directory");
let location_path = location.path();
let downloader = Downloader::new(location_path.to_path_buf());
let result = downloader
.download(
"https://github.com/imsnif/multitask/releases/download/0.38.2v2/multitask.wasm",
None,
)
.await
.is_ok();
assert!(result);
assert!(location_path.join("multitask.wasm").exists());
location.close().expect("Failed to close temp directory");
}
}
|