Skip to content

Commit 9723b3f

Browse files
fix(download): stop corrupting BuildKit layers when a cache download resumes (#316)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a13ebc8 commit 9723b3f

10 files changed

Lines changed: 236 additions & 79 deletions

File tree

‎src/routes/transfer.rs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ use crate::storage::{
2323

2424
/// Clients without a request id intermittently fail with EOF (tonistiigi/go-actions-cache).
2525
const REQUEST_ID: HeaderName = HeaderName::from_static("x-ms-request-id");
26+
/// Azure's Range header; Get Blob prefers it over `Range`.
27+
const X_MS_RANGE: HeaderName = HeaderName::from_static("x-ms-range");
2628

2729
/// Lenient like Node's `Buffer.from(value, 'base64')`.
2830
const BASE64: GeneralPurpose = GeneralPurpose::new(
@@ -128,9 +130,15 @@ fn upload_not_found(upload_id: i64) -> HttpError {
128130
}
129131

130132
/// A single range; multi-range requests and invalid headers, which includes inverted ranges, are
131-
/// served whole.
133+
/// served whole. `x-ms-range` wins over `Range`, like Azure Get Blob: the Azure SDK, and with it
134+
/// `BuildKit`'s `type=gha` cache, sends only `x-ms-range` when it resumes a download.
132135
fn parse_range(headers: &HeaderMap) -> Option<RangeRequest> {
133-
let value = headers.get(RANGE)?.to_str().ok()?.trim();
136+
let value = headers
137+
.get(X_MS_RANGE)
138+
.or_else(|| headers.get(RANGE))?
139+
.to_str()
140+
.ok()?
141+
.trim();
134142
// The unit is case-insensitive (RFC 9110 §14.1); the parser only knows `bytes=`.
135143
let ranges = value
136144
.get(..6)?
@@ -153,7 +161,6 @@ pub(super) async fn download(
153161
headers: HeaderMap,
154162
) -> Result<Response, HttpError> {
155163
let range = parse_range(&headers);
156-
// Unmerged entries ignore Range, so clients must key off the status, not this header.
157164
let accept_ranges = (ACCEPT_RANGES, HeaderValue::from_static("bytes"));
158165
let download = match state.storage.download(&location_id, range).await {
159166
Ok(Some(download)) => download,

‎src/routes/transfer/tests.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,28 @@ fn parses_single_ranges() {
5252
assert_eq!(range("bytes=9-5"), None, "inverted");
5353
assert_eq!(range("items=0-5"), None, "unknown unit");
5454
}
55+
56+
#[test]
57+
fn x_ms_range_wins_over_range() {
58+
let from = |pairs: &[(&'static str, &'static str)]| {
59+
let mut headers = HeaderMap::new();
60+
for &(name, value) in pairs {
61+
headers.insert(name, HeaderValue::from_static(value));
62+
}
63+
parse_range(&headers)
64+
};
65+
let from_100 = Some(RangeRequest {
66+
start: StartPosition::Index(100),
67+
end: EndPosition::LastByte,
68+
});
69+
assert_eq!(
70+
from(&[("x-ms-range", "bytes=100-")]),
71+
from_100,
72+
"x-ms-range alone, as the Azure SDK sends it"
73+
);
74+
assert_eq!(
75+
from(&[("x-ms-range", "bytes=100-"), ("range", "bytes=0-9")]),
76+
from_100,
77+
"x-ms-range wins, like Azure Get Blob"
78+
);
79+
}

‎src/storage.rs‎

Lines changed: 82 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use axum::body::Bytes;
1515
use base64::Engine as _;
1616
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1717
use futures_util::future::BoxFuture;
18-
use futures_util::{FutureExt as _, StreamExt as _, TryStreamExt as _, stream};
18+
use futures_util::{FutureExt as _, StreamExt as _, TryStreamExt as _, future, stream};
1919
use sea_orm::ActiveValue::Set;
2020
use sea_orm::sea_query::{CaseStatement, Expr, ExprTrait as _, Func};
2121
use sea_orm::{
@@ -30,11 +30,11 @@ use tokio_stream::wrappers::ReceiverStream;
3030
use tokio_util::task::{AbortOnDropHandle, TaskTracker};
3131
use utoipa::ToSchema;
3232

33-
use self::adapter::ReadError;
3433
pub(crate) use self::adapter::{
3534
Adapter, ByteStream, DownloadStream, EndPosition, Extent, RangeRequest, StartPosition,
3635
UploadKind,
3736
};
37+
use self::adapter::{ReadError, clamp_range};
3838
use self::leases::{
3939
DIRECT_DOWNLOAD_LEASE_MARGIN, LEASE_DURATION, LEASE_RENEWAL, acquire_merge_lease,
4040
create_reader_lease, deadline, release_merge_lease, release_reader_lease, renew_merge_lease,
@@ -171,8 +171,13 @@ fn entry_identity(identity: &EntryIdentity) -> Condition {
171171
.add(cache_entries::COLUMN.repo_id.eq(identity.repo_id.as_str()))
172172
}
173173

174-
/// Concatenates a location's Parts as they are read.
175-
fn stream_parts(adapter: Arc<Adapter>, location: &StorageLocation) -> ByteStream {
174+
/// Concatenates a location's Parts as they are read, from `skip` bytes into Part `first`.
175+
fn stream_parts(
176+
adapter: Arc<Adapter>,
177+
location: &StorageLocation,
178+
first: i32,
179+
skip: u64,
180+
) -> ByteStream {
176181
if location.parts_deleted_at.is_some() {
177182
return stream::once(async {
178183
Err(io::Error::other(
@@ -182,13 +187,17 @@ fn stream_parts(adapter: Arc<Adapter>, location: &StorageLocation) -> ByteStream
182187
.boxed();
183188
}
184189
let folder = location.folder_name.clone();
185-
stream::iter(0..location.part_count)
190+
stream::iter(first..location.part_count)
186191
.then(move |index| {
187192
let adapter = Arc::clone(&adapter);
188193
let name = part_object(&folder, index);
194+
let range = (index == first && skip > 0).then_some(RangeRequest {
195+
start: StartPosition::Index(skip),
196+
end: EndPosition::LastByte,
197+
});
189198
async move {
190199
adapter
191-
.download_stream(&name, None)
200+
.download_stream(&name, range)
192201
.await
193202
.map(|download| download.stream)
194203
.map_err(io::Error::other)
@@ -198,6 +207,24 @@ fn stream_parts(adapter: Arc<Adapter>, location: &StorageLocation) -> ByteStream
198207
.boxed()
199208
}
200209

210+
/// The first `len` bytes of a stream.
211+
fn take_bytes(stream: ByteStream, len: u64) -> ByteStream {
212+
stream
213+
.scan(len, |left, chunk| {
214+
let chunk = match chunk {
215+
Ok(_) if *left == 0 => None,
216+
Ok(mut bytes) => {
217+
bytes.truncate(usize::try_from(*left).unwrap_or(usize::MAX));
218+
*left = left.saturating_sub(u64::try_from(bytes.len()).unwrap_or(u64::MAX));
219+
Some(Ok(bytes))
220+
}
221+
Err(error) => Some(Err(error)),
222+
};
223+
future::ready(chunk)
224+
})
225+
.boxed()
226+
}
227+
201228
/// Releases a Storage Reader Lease and stops its renewal once the protected stream is dropped.
202229
struct LeaseGuard {
203230
db: Db,
@@ -361,13 +388,18 @@ impl Storage {
361388
.boxed()
362389
}
363390

364-
async fn ensure_parts_exist(&self, location: &StorageLocation) -> Result<(), ReadError> {
391+
/// The sizes of a location's Parts in order, from one listing; `NotFound` when one is gone.
392+
async fn part_sizes(&self, location: &StorageLocation) -> Result<Vec<u64>, ReadError> {
365393
let folder = parts_folder(&location.folder_name);
366394
let parts = self.adapter.list_folder(&folder).await?;
367-
if parts.len() < usize::try_from(location.part_count).unwrap_or(0) {
368-
return Err(ReadError::NotFound(folder));
369-
}
370-
Ok(())
395+
(0..location.part_count)
396+
.map(|index| {
397+
parts
398+
.get(&index.to_string())
399+
.copied()
400+
.ok_or_else(|| ReadError::NotFound(folder.clone()))
401+
})
402+
.collect()
371403
}
372404

373405
async fn download_location(
@@ -378,12 +410,38 @@ impl Storage {
378410
if let Some((object, _)) = whole_object(location) {
379411
return self.adapter.download_stream(&object, range).await;
380412
}
381-
self.ensure_parts_exist(location).await?;
382-
// No range: an unmerged entry is concatenated from its parts as it is read, so there is
383-
// nothing to seek into. Served whole under a 200, which Range allows.
413+
let part_sizes = self.part_sizes(location).await?;
414+
let adapter = Arc::clone(&self.adapter);
415+
let size = part_sizes
416+
.iter()
417+
.fold(0_u64, |total, &part| total.saturating_add(part));
418+
let Some(range) = range.filter(|_| size > 0) else {
419+
// An unmerged entry is concatenated from its Parts as it is read. Only an empty entry
420+
// ignores a range, like an empty object does.
421+
return Ok(DownloadStream {
422+
stream: stream_parts(adapter, location, 0, 0),
423+
extent: Extent::Unsized,
424+
});
425+
};
426+
// Never the whole entry under a 200: the Azure SDK takes any 200 body as the bytes from
427+
// the offset it asked for.
428+
let served = clamp_range(range, size)
429+
.ok_or_else(|| ReadError::RangeNotSatisfiable(parts_folder(&location.folder_name)))?;
430+
// The Part the range starts in, and the offset into it.
431+
let (mut first, mut skip) = (0_i32, served.start);
432+
for &part in &part_sizes {
433+
if skip < part {
434+
break;
435+
}
436+
skip = skip.saturating_sub(part);
437+
first = first.saturating_add(1);
438+
}
384439
Ok(DownloadStream {
385-
stream: stream_parts(Arc::clone(&self.adapter), location),
386-
extent: Extent::Unsized,
440+
stream: take_bytes(stream_parts(adapter, location, first, skip), served.len()),
441+
extent: Extent::Partial {
442+
range: served,
443+
size,
444+
},
387445
})
388446
}
389447

@@ -509,7 +567,7 @@ impl Storage {
509567
fn merge_parts(&self, location: &StorageLocation) -> BoxFuture<'static, Result<()>> {
510568
let adapter = Arc::clone(&self.adapter);
511569
let merged = merged_object(&location.folder_name);
512-
let part_stream = stream_parts(Arc::clone(&adapter), location);
570+
let part_stream = stream_parts(Arc::clone(&adapter), location, 0, 0);
513571
let kind = UploadKind::Merged {
514572
length: location
515573
.size_bytes
@@ -668,7 +726,7 @@ impl Storage {
668726
return Err(self.abandon_upload(&upload, reason).await);
669727
}
670728
let size_bytes = parts
671-
.iter()
729+
.values()
672730
.fold(0_u64, |total, bytes| total.saturating_add(*bytes));
673731
let location = StorageLocation {
674732
id: uuid::Uuid::new_v4().to_string(),
@@ -871,16 +929,17 @@ impl Storage {
871929
location: &StorageLocation,
872930
range: Option<RangeRequest>,
873931
) -> Result<DownloadStream, ReadError> {
874-
if whole_object(location).is_some() {
932+
// A ranged read serves its slice from the Parts and leaves the Merge to a whole read.
933+
if whole_object(location).is_some() || range.is_some() {
875934
return self.download_location(location, range).await;
876935
}
877-
self.ensure_parts_exist(location).await?;
936+
self.part_sizes(location).await?;
878937

879938
// Local Parts are cheap to read twice, so the client reads them at its own pace while
880939
// the Merge copies them in the background.
881940
if let Adapter::Filesystem(_) = self.adapter.as_ref() {
882941
self.start_merge_detached(location, self.merge_parts(location));
883-
return self.download_location(location, range).await;
942+
return self.download_location(location, None).await;
884943
}
885944
// Object storage is read once and teed into the response and the Merge.
886945
let (merger_sender, merger_receiver) = mpsc::channel(1);
@@ -900,11 +959,11 @@ impl Storage {
900959
.boxed()
901960
};
902961
if !self.start_merge(location, write).await? {
903-
return self.download_location(location, range).await;
962+
return self.download_location(location, None).await;
904963
}
905964
let (response_sender, response_receiver) = mpsc::channel(1);
906965
drop(tokio::spawn(pump_parts(
907-
stream_parts(Arc::clone(&self.adapter), location),
966+
stream_parts(Arc::clone(&self.adapter), location, 0, 0),
908967
response_sender,
909968
merger_sender,
910969
)));

‎src/storage/adapter.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Storage backends behind one interface.
22
3+
use std::collections::HashMap;
34
use std::io;
45

56
use axum::body::Bytes;
@@ -215,8 +216,8 @@ impl Adapter {
215216
}
216217
}
217218

218-
/// Sizes of the objects under a folder.
219-
pub(crate) async fn list_folder(&self, folder: &str) -> Result<Vec<u64>> {
219+
/// Sizes of the objects under a folder, by name relative to it.
220+
pub(crate) async fn list_folder(&self, folder: &str) -> Result<HashMap<String, u64>> {
220221
match self {
221222
Self::Filesystem(adapter) => adapter.list_folder(folder).await,
222223
Self::Object(adapter) => adapter.list_folder(folder).await,

‎src/storage/filesystem.rs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Storage on a local (or mounted) filesystem.
22
3+
use std::collections::HashMap;
34
use std::io::{self, SeekFrom};
45
use std::path::{Component, Path, PathBuf};
56
use std::time::UNIX_EPOCH;
@@ -221,18 +222,19 @@ impl FilesystemAdapter {
221222
})
222223
}
223224

224-
pub(crate) async fn list_folder(&self, folder: &str) -> Result<Vec<u64>> {
225+
pub(crate) async fn list_folder(&self, folder: &str) -> Result<HashMap<String, u64>> {
225226
let mut entries = match fs::read_dir(self.safe_path(folder)?).await {
226227
Ok(entries) => entries,
227-
Err(error) if is_not_found(&error) => return Ok(Vec::new()),
228+
Err(error) if is_not_found(&error) => return Ok(HashMap::new()),
228229
Err(error) => return Err(error.into()),
229230
};
230-
let mut objects = Vec::new();
231+
let mut objects = HashMap::new();
231232
while let Some(entry) = entries.next_entry().await? {
232233
if entry.file_type().await?.is_dir() {
233234
continue;
234235
}
235-
objects.push(fs::metadata(entry.path()).await?.len());
236+
let size = fs::metadata(entry.path()).await?.len();
237+
objects.insert(entry.file_name().to_string_lossy().into_owned(), size);
236238
}
237239
Ok(objects)
238240
}

‎src/storage/object.rs‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -476,11 +476,16 @@ impl ObjectAdapter {
476476
self.delete_prefix(&self.path(folder)).await
477477
}
478478

479-
pub(crate) async fn list_folder(&self, folder: &str) -> Result<Vec<u64>> {
479+
pub(crate) async fn list_folder(&self, folder: &str) -> Result<HashMap<String, u64>> {
480+
let folder = self.path(folder);
480481
self.store
481-
.list(Some(&self.path(folder)))
482+
.list(Some(&folder))
482483
.map_err(Failure::from)
483-
.map_ok(|object| object.size)
484+
.map_ok(|object| {
485+
let name = object.location.as_ref().strip_prefix(folder.as_ref());
486+
let name = name.unwrap_or_default().trim_start_matches('/');
487+
(name.to_owned(), object.size)
488+
})
484489
.try_collect()
485490
.await
486491
}

0 commit comments

Comments
 (0)