@@ -15,7 +15,7 @@ use axum::body::Bytes;
1515use base64:: Engine as _;
1616use base64:: engine:: general_purpose:: URL_SAFE_NO_PAD ;
1717use 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} ;
1919use sea_orm:: ActiveValue :: Set ;
2020use sea_orm:: sea_query:: { CaseStatement , Expr , ExprTrait as _, Func } ;
2121use sea_orm:: {
@@ -30,11 +30,11 @@ use tokio_stream::wrappers::ReceiverStream;
3030use tokio_util:: task:: { AbortOnDropHandle , TaskTracker } ;
3131use utoipa:: ToSchema ;
3232
33- use self :: adapter:: ReadError ;
3433pub ( crate ) use self :: adapter:: {
3534 Adapter , ByteStream , DownloadStream , EndPosition , Extent , RangeRequest , StartPosition ,
3635 UploadKind ,
3736} ;
37+ use self :: adapter:: { ReadError , clamp_range} ;
3838use 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.
202229struct 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 ) ) ) ;
0 commit comments