capsule_sdk/fetch/resumable.rs
1//! File-backed resumable download (SSoT: [Download & Sync] §Resumption and Verification).
2//!
3//! [`RangedFetcher::fetch_to_file`] lands a blob at a destination path through a partial file
4//! beside it ([`partial_path`]):
5//!
6//! - **The partial's length is the resume position.** Each window is written and then
7//! `fsync`ed before the next is requested, so the length a later attempt reads never counts a
8//! byte that is not on disk. There is no separate counter that could run ahead of the data.
9//! - **Resume across a restart.** A new attempt — in this process or the next — hashes the
10//! bytes the partial already holds and asks the source only for the rest.
11//! - **Atomic landing.** The destination name appears only by a `rename` of the partial after
12//! the content address verifies over every byte, so no reader ever sees a partial or
13//! unverified file under the final name.
14//! - **A corrupt partial is discarded.** A content-address mismatch deletes the partial (it
15//! cannot be trusted as a prefix of anything); so does a partial longer than the blob. The
16//! caller's next attempt starts from zero.
17//!
18//! Any other failure — transient, stalled, refused, a local I/O error — keeps the partial, so
19//! the next attempt resumes from it. The partial is keyed by the destination path, so one
20//! destination names one content address: a partial left by a different blob fails
21//! verification and is discarded, never renamed into place.
22//!
23//! [Download & Sync]: https://docs/design/transfer/download/
24
25use std::fs::{self, File, OpenOptions};
26use std::io::{self, Read, Seek, SeekFrom};
27use std::path::{Path, PathBuf};
28
29use sha2::{Digest, Sha256};
30use tracing::instrument;
31
32use super::{BlobSource, FetchError, RangedFetcher, Resume};
33use crate::net::{ConnectionClass, MonotonicClock, Sleeper, TransferSignal};
34
35/// The suffix [`partial_path`] appends to a destination's file name.
36pub const PARTIAL_SUFFIX: &str = ".partial";
37
38/// The read buffer used to re-hash a partial on resume: bounded, whatever the partial's size.
39const REHASH_BUFFER: usize = 64 * 1024;
40
41/// The partial file a download to `dest` is written to before it is renamed into place:
42/// `dest` with [`PARTIAL_SUFFIX`] appended, in the same directory so the rename stays on one
43/// filesystem and is atomic.
44#[must_use]
45pub fn partial_path(dest: &Path) -> PathBuf {
46 let mut name = dest.as_os_str().to_owned();
47 name.push(PARTIAL_SUFFIX);
48 PathBuf::from(name)
49}
50
51impl<S: Sleeper, C: MonotonicClock> RangedFetcher<S, C> {
52 /// Fetch a whole blob into the file `dest`, resumable across a process restart, and make it
53 /// visible under `dest` only once its content address verifies.
54 ///
55 /// Bytes land in [`partial_path`]`(dest)`, one bounded window at a time (as
56 /// [`fetch_into`](Self::fetch_into)), each `fsync`ed before the next is requested. An
57 /// attempt that finds a partial already there re-hashes it in bounded memory and resumes
58 /// from its length. On success the partial is synced and atomically renamed over `dest`;
59 /// the directory holding `dest` is then synced, and a failure of that last sync is logged,
60 /// not returned, because the verified blob has already landed.
61 ///
62 /// On [`FetchError::IntegrityFailed`] the partial is deleted and `dest` is untouched. Every
63 /// other error leaves the partial for the next attempt to resume. `dest`'s directory must
64 /// exist.
65 #[instrument(skip(self, source, dest), fields(dest = %dest.display(), class = ?self.class))]
66 pub async fn fetch_to_file<B: BlobSource>(
67 &self,
68 source: &B,
69 hash: &str,
70 expected_len: u64,
71 dest: &Path,
72 ) -> Result<Vec<TransferSignal>, FetchError> {
73 let partial = partial_path(dest);
74 let (mut file, resume) = open_partial(&partial, expected_len).map_err(FetchError::Sink)?;
75 if resume.held > 0 {
76 tracing::info!(
77 hash,
78 held = resume.held,
79 expected_len,
80 "resuming download from its partial file"
81 );
82 } else {
83 tracing::debug!(hash, expected_len, "starting download into a partial file");
84 }
85 let outcome = self
86 .run_from(
87 source,
88 hash,
89 expected_len,
90 self.sink_window(),
91 resume,
92 &mut file,
93 |file: &mut File| file.sync_data(),
94 )
95 .await;
96 match outcome {
97 Ok(signals) => {
98 file.sync_all().map_err(FetchError::Sink)?;
99 drop(file);
100 land(&partial, dest).map_err(FetchError::Sink)?;
101 tracing::info!(
102 hash,
103 expected_len,
104 "download verified and renamed into place"
105 );
106 Ok(signals)
107 }
108 Err(error @ FetchError::IntegrityFailed { .. }) => {
109 drop(file);
110 discard(&partial);
111 Err(error)
112 }
113 Err(error) => {
114 tracing::debug!(hash, %error, "download interrupted; partial kept for resume");
115 Err(error)
116 }
117 }
118 }
119}
120
121/// Fetch a whole blob into the file `dest` — the unmetered convenience over
122/// [`RangedFetcher::fetch_to_file`], the file-backed counterpart of
123/// [`fetch_blob_into`](super::fetch_blob_into).
124pub async fn fetch_blob_to_file<S: BlobSource>(
125 source: &S,
126 hash: &str,
127 expected_len: u64,
128 dest: &Path,
129) -> Result<(), FetchError> {
130 RangedFetcher::new(ConnectionClass::Unmetered)
131 .fetch_to_file(source, hash, expected_len, dest)
132 .await
133 .map(drop)
134}
135
136/// Open (or create) the partial, positioned at its end, with the hash of what it holds.
137///
138/// A partial longer than the blob cannot be a prefix of it, so it is truncated and the fetch
139/// starts over.
140fn open_partial(partial: &Path, expected_len: u64) -> io::Result<(File, Resume)> {
141 let mut file = OpenOptions::new()
142 .read(true)
143 .write(true)
144 .create(true)
145 .truncate(false)
146 .open(partial)?;
147 let mut held = file.metadata()?.len();
148 if held > expected_len {
149 tracing::warn!(
150 partial = %partial.display(),
151 held,
152 expected_len,
153 "partial is longer than the blob; discarding it"
154 );
155 file.set_len(0)?;
156 file.sync_data()?;
157 held = 0;
158 }
159 let mut hasher = Sha256::new();
160 let mut buffer = vec![0u8; REHASH_BUFFER];
161 let mut hashed: u64 = 0;
162 file.seek(SeekFrom::Start(0))?;
163 while hashed < held {
164 let read = file.read(&mut buffer)?;
165 if read == 0 {
166 break;
167 }
168 hasher.update(&buffer[..read]);
169 hashed += read as u64;
170 }
171 if hashed != held {
172 return Err(io::Error::new(
173 io::ErrorKind::UnexpectedEof,
174 format!("partial reported {held} bytes but {hashed} could be read"),
175 ));
176 }
177 file.seek(SeekFrom::Start(held))?;
178 Ok((file, Resume { held, hasher }))
179}
180
181/// Rename the verified partial over `dest`, then make the rename itself durable.
182///
183/// Only a failed rename is an error: the partial is then still in place for the next attempt.
184/// Once the rename returns, the verified blob is at `dest` and the partial is gone, so a failure
185/// to `fsync` the parent directory is logged rather than raised. A crash before the directory
186/// reaches disk can at worst revert the rename, which brings back the complete partial; the next
187/// attempt re-verifies it and lands it without fetching a byte.
188fn land(partial: &Path, dest: &Path) -> io::Result<()> {
189 fs::rename(partial, dest)?;
190 if let Err(error) = sync_parent(dest) {
191 tracing::warn!(
192 dest = %dest.display(),
193 %error,
194 "download landed but its directory could not be synced; the rename may not survive a crash"
195 );
196 }
197 Ok(())
198}
199
200/// `fsync` the directory holding `path`, so a rename into it survives a crash. Windows has no
201/// directory handle to sync; its rename is already durable once it returns.
202#[cfg(unix)]
203fn sync_parent(path: &Path) -> io::Result<()> {
204 let parent = match path.parent() {
205 Some(parent) if !parent.as_os_str().is_empty() => parent,
206 _ => Path::new("."),
207 };
208 File::open(parent)?.sync_all()
209}
210
211#[cfg(not(unix))]
212fn sync_parent(_path: &Path) -> io::Result<()> {
213 Ok(())
214}
215
216/// Delete a partial that failed verification. A failure to delete is logged, not raised: the
217/// verification error is the one the caller acts on, and the next attempt re-verifies anyway.
218fn discard(partial: &Path) {
219 match fs::remove_file(partial) {
220 Ok(()) => tracing::warn!(
221 partial = %partial.display(),
222 "partial failed content-address verification; discarded"
223 ),
224 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
225 Err(error) => tracing::error!(
226 partial = %partial.display(),
227 %error,
228 "partial failed verification and could not be deleted"
229 ),
230 }
231}