hdiff-update-core 0.2.0

Core library for signed, transactional HDiffPatch directory updates.
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use std::{
    path::{Path, PathBuf},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use url::Url;

use crate::{error::io_path, fs_ops::replace_file, Error, Result};

const MAX_TEXT_RESPONSE_BYTES: u64 = 4 * 1024 * 1024;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HttpHeader {
    pub name: String,
    pub value: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "event", content = "data", rename_all = "camelCase")]
pub enum DownloadEvent {
    Started { content_length: Option<u64> },
    Progress { chunk_length: usize },
    Finished,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadStats {
    pub path: PathBuf,
    pub bytes_written: u64,
}

pub async fn read_url_to_string(
    url_or_path: &str,
    headers: &[HttpHeader],
    timeout_secs: Option<u64>,
) -> Result<String> {
    if let Some(url) = parse_supported_url_or_path(url_or_path)? {
        match url.scheme() {
            "http" | "https" => {
                let client = client(timeout_secs)?;
                let mut request = client.get(url);
                for header in headers {
                    request = request.header(&header.name, &header.value);
                }
                let response = request.send().await?;
                ensure_success_status(&response)?;
                return response_text_limited(response).await;
            }
            "file" => {
                let path = url
                    .to_file_path()
                    .map_err(|_| Error::UnsupportedUrl(url_or_path.to_string()))?;
                return read_text_file_limited(&path).await;
            }
            _ => return Err(Error::UnsupportedUrl(url_or_path.to_string())),
        }
    }

    read_text_file_limited(Path::new(url_or_path)).await
}

async fn response_text_limited(response: reqwest::Response) -> Result<String> {
    if response
        .content_length()
        .is_some_and(|length| length > MAX_TEXT_RESPONSE_BYTES)
    {
        return Err(Error::DownloadLimitExceeded {
            limit: MAX_TEXT_RESPONSE_BYTES,
            attempted: response.content_length().unwrap_or_default(),
        });
    }
    let mut stream = response.bytes_stream();
    let mut bytes = Vec::new();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        let attempted = bytes.len() as u64 + chunk.len() as u64;
        if attempted > MAX_TEXT_RESPONSE_BYTES {
            return Err(Error::DownloadLimitExceeded {
                limit: MAX_TEXT_RESPONSE_BYTES,
                attempted,
            });
        }
        bytes.extend_from_slice(&chunk);
    }
    String::from_utf8(bytes)
        .map_err(|error| Error::Message(format!("text response is not valid UTF-8: {error}")))
}

async fn read_text_file_limited(path: &Path) -> Result<String> {
    let metadata = tokio::fs::metadata(path)
        .await
        .map_err(|error| io_path(path, error))?;
    if metadata.len() > MAX_TEXT_RESPONSE_BYTES {
        return Err(Error::DownloadLimitExceeded {
            limit: MAX_TEXT_RESPONSE_BYTES,
            attempted: metadata.len(),
        });
    }
    tokio::fs::read_to_string(path)
        .await
        .map_err(|error| io_path(path, error))
}

pub async fn download_to_file<F>(
    url_or_path: &str,
    destination: impl AsRef<Path>,
    headers: &[HttpHeader],
    timeout_secs: Option<u64>,
    maximum_bytes: Option<u64>,
    on_event: F,
) -> Result<DownloadStats>
where
    F: FnMut(DownloadEvent),
{
    let destination = destination.as_ref();
    if let Some(parent) = destination.parent() {
        tokio::fs::create_dir_all(parent)
            .await
            .map_err(|error| io_path(parent, error))?;
    }

    let temporary_destination = temporary_path_for(destination);
    let result = download_to_temporary_file(
        url_or_path,
        &temporary_destination,
        headers,
        timeout_secs,
        maximum_bytes,
        on_event,
    )
    .await;

    match result {
        Ok(mut stats) => {
            let temporary = temporary_destination.clone();
            let destination_path = destination.to_path_buf();
            tokio::task::spawn_blocking(move || replace_file(&temporary, &destination_path))
                .await
                .map_err(|error| {
                    Error::Message(format!("download replace task failed: {error}"))
                })??;
            stats.path = destination.to_path_buf();
            Ok(stats)
        }
        Err(error) => {
            let _ = tokio::fs::remove_file(&temporary_destination).await;
            Err(error)
        }
    }
}

async fn download_to_temporary_file<F>(
    url_or_path: &str,
    destination: &Path,
    headers: &[HttpHeader],
    timeout_secs: Option<u64>,
    maximum_bytes: Option<u64>,
    on_event: F,
) -> Result<DownloadStats>
where
    F: FnMut(DownloadEvent),
{
    if let Some(url) = parse_supported_url_or_path(url_or_path)? {
        return match url.scheme() {
            "http" | "https" => {
                download_http(
                    url,
                    destination,
                    headers,
                    timeout_secs,
                    maximum_bytes,
                    on_event,
                )
                .await
            }
            "file" => {
                let source = url
                    .to_file_path()
                    .map_err(|_| Error::UnsupportedUrl(url_or_path.to_string()))?;
                copy_file_with_progress(&source, destination, maximum_bytes, on_event).await
            }
            _ => Err(Error::UnsupportedUrl(url_or_path.to_string())),
        };
    }

    copy_file_with_progress(url_or_path, destination, maximum_bytes, on_event).await
}

fn parse_supported_url_or_path(value: &str) -> Result<Option<Url>> {
    match Url::parse(value) {
        Ok(url) if matches!(url.scheme(), "http" | "https" | "file") => Ok(Some(url)),
        Ok(_) if value.contains("://") => Err(Error::UnsupportedUrl(value.to_string())),
        Ok(_) | Err(_) => Ok(None),
    }
}

async fn download_http<F>(
    url: Url,
    destination: &Path,
    headers: &[HttpHeader],
    timeout_secs: Option<u64>,
    maximum_bytes: Option<u64>,
    mut on_event: F,
) -> Result<DownloadStats>
where
    F: FnMut(DownloadEvent),
{
    let client = client(timeout_secs)?;
    let mut request = client.get(url);
    for header in headers {
        request = request.header(&header.name, &header.value);
    }

    let response = request.send().await?;
    ensure_success_status(&response)?;
    let content_length = response.content_length();
    if let (Some(limit), Some(content_length)) = (maximum_bytes, content_length) {
        if content_length > limit {
            return Err(Error::DownloadLimitExceeded {
                limit,
                attempted: content_length,
            });
        }
    }
    on_event(DownloadEvent::Started { content_length });

    let mut stream = response.bytes_stream();
    let mut file = tokio::fs::File::create(destination)
        .await
        .map_err(|error| io_path(destination, error))?;
    let mut written = 0_u64;

    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        let attempted = written
            .checked_add(chunk.len() as u64)
            .ok_or_else(|| Error::Message("download size overflow".to_string()))?;
        if maximum_bytes.is_some_and(|limit| attempted > limit) {
            return Err(Error::DownloadLimitExceeded {
                limit: maximum_bytes.unwrap_or_default(),
                attempted,
            });
        }
        file.write_all(&chunk)
            .await
            .map_err(|error| io_path(destination, error))?;
        written = attempted;
        on_event(DownloadEvent::Progress {
            chunk_length: chunk.len(),
        });
    }

    file.flush()
        .await
        .map_err(|error| io_path(destination, error))?;
    file.sync_all()
        .await
        .map_err(|error| io_path(destination, error))?;
    on_event(DownloadEvent::Finished);

    Ok(DownloadStats {
        path: destination.to_path_buf(),
        bytes_written: written,
    })
}

async fn copy_file_with_progress<F>(
    source: impl AsRef<Path>,
    destination: impl AsRef<Path>,
    maximum_bytes: Option<u64>,
    mut on_event: F,
) -> Result<DownloadStats>
where
    F: FnMut(DownloadEvent),
{
    let source = source.as_ref();
    let destination = destination.as_ref();
    let mut input = tokio::fs::File::open(source)
        .await
        .map_err(|error| io_path(source, error))?;
    let metadata = input
        .metadata()
        .await
        .map_err(|error| io_path(source, error))?;
    if maximum_bytes.is_some_and(|limit| metadata.len() > limit) {
        return Err(Error::DownloadLimitExceeded {
            limit: maximum_bytes.unwrap_or_default(),
            attempted: metadata.len(),
        });
    }
    let mut output = tokio::fs::File::create(destination)
        .await
        .map_err(|error| io_path(destination, error))?;
    let mut buf = vec![0_u8; 256 * 1024];
    let mut written = 0_u64;

    on_event(DownloadEvent::Started {
        content_length: Some(metadata.len()),
    });
    loop {
        let read = input
            .read(&mut buf)
            .await
            .map_err(|error| io_path(source, error))?;
        if read == 0 {
            break;
        }
        let attempted = written
            .checked_add(read as u64)
            .ok_or_else(|| Error::Message("download size overflow".to_string()))?;
        if maximum_bytes.is_some_and(|limit| attempted > limit) {
            return Err(Error::DownloadLimitExceeded {
                limit: maximum_bytes.unwrap_or_default(),
                attempted,
            });
        }
        output
            .write_all(&buf[..read])
            .await
            .map_err(|error| io_path(destination, error))?;
        written = attempted;
        on_event(DownloadEvent::Progress { chunk_length: read });
    }

    output
        .flush()
        .await
        .map_err(|error| io_path(destination, error))?;
    output
        .sync_all()
        .await
        .map_err(|error| io_path(destination, error))?;
    on_event(DownloadEvent::Finished);

    Ok(DownloadStats {
        path: destination.to_path_buf(),
        bytes_written: written,
    })
}

fn client(timeout_secs: Option<u64>) -> Result<reqwest::Client> {
    let mut builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
    if let Some(timeout_secs) = timeout_secs {
        builder = builder.timeout(Duration::from_secs(timeout_secs));
    }
    Ok(builder.build()?)
}

fn ensure_success_status(response: &reqwest::Response) -> Result<()> {
    if response.status().is_success() {
        return Ok(());
    }
    Err(Error::UnexpectedHttpStatus {
        status: response.status().as_u16(),
    })
}

fn temporary_path_for(destination: &Path) -> PathBuf {
    let file_name = destination
        .file_name()
        .map(|name| name.to_string_lossy())
        .unwrap_or_else(|| "download".into());
    let suffix = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or_default();
    destination.with_file_name(format!(".{file_name}.part-{}-{suffix}", std::process::id()))
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::tempdir;

    use super::download_to_file;
    use crate::Error;

    #[tokio::test]
    async fn local_download_stops_at_the_signed_size_limit() {
        let dir = tempdir().unwrap();
        let source = dir.path().join("source.bin");
        let destination = dir.path().join("destination.bin");
        fs::write(&source, b"0123456789").unwrap();

        let error = download_to_file(
            source.to_str().unwrap(),
            &destination,
            &[],
            None,
            Some(5),
            |_| {},
        )
        .await
        .unwrap_err();

        assert!(matches!(error, Error::DownloadLimitExceeded { .. }));
        assert!(!destination.exists());
    }
}