Skip to main content

instapi360_cloud/
download.rs

1//! Streaming, resumable downloads of file parts from OSS signed URLs.
2//!
3//! The core [`download_part`] takes any `AsyncWrite` sink and an optional
4//! starting offset (HTTP `Range`) so it serves both the CLI (writing to a file)
5//! and a future Android caller without the core crate touching the filesystem.
6
7use futures::StreamExt;
8use tokio::io::{AsyncWrite, AsyncWriteExt};
9
10use crate::client::Client;
11use crate::error::{Error, Result};
12use crate::model::FilePart;
13
14/// Progress callback: `(bytes_done, total_bytes_if_known)`.
15pub trait ProgressSink: FnMut(u64, Option<u64>) {}
16impl<T: FnMut(u64, Option<u64>)> ProgressSink for T {}
17
18impl Client {
19    /// Stream one [`FilePart`] into `sink`, resuming from byte `from`.
20    ///
21    /// * `from` — resume offset; pass 0 for a fresh download. Sent as an HTTP
22    ///   `Range: bytes=from-` header.
23    /// * `progress` — invoked as bytes arrive with the running total.
24    ///
25    /// On a `403` (OSS URL expired) the caller should re-`resolve_download` and
26    /// retry with the new URL and the same `from`.
27    pub async fn download_part<W, P>(
28        &self,
29        part: &FilePart,
30        mut sink: W,
31        from: u64,
32        mut progress: P,
33    ) -> Result<()>
34    where
35        W: AsyncWrite + Unpin,
36        P: ProgressSink,
37    {
38        let mut req = self.http().get(&part.url);
39        if from > 0 {
40            req = req.header(reqwest::header::RANGE, format!("bytes={from}-"));
41        }
42        let resp = req.send().await?;
43        let status = resp.status();
44        if status == reqwest::StatusCode::FORBIDDEN {
45            return Err(Error::Auth(
46                "OSS url expired (403) — re-resolve download".into(),
47            ));
48        }
49        let resp = resp.error_for_status()?;
50
51        // Total = declared part size when known, else content-length + offset.
52        let content_len = resp.content_length();
53        let total = if part.size > 0 {
54            Some(part.size)
55        } else {
56            content_len.map(|c| c + from)
57        };
58
59        let mut done = from;
60        progress(done, total);
61
62        let mut stream = resp.bytes_stream();
63        while let Some(chunk) = stream.next().await {
64            let chunk = chunk?;
65            sink.write_all(&chunk).await?;
66            done += chunk.len() as u64;
67            progress(done, total);
68        }
69        sink.flush().await?;
70
71        if let Some(t) = total {
72            if done < t {
73                return Err(Error::Partial {
74                    got: done,
75                    expected: t,
76                });
77            }
78        }
79        Ok(())
80    }
81}