From 354df01d36df4c36a279db0cfb9c99803a97fab6 Mon Sep 17 00:00:00 2001 From: Nandan Varma Date: Tue, 6 Oct 2026 22:22:36 -0700 Subject: [PATCH 1/2] Resume blob downloads after a dropped connection --- .../Client/RegistryClient+Fetch.swift | 162 +++++++++--- .../BlobResumeTests.swift | 245 ++++++++++++++++++ .../ResolveDigestHeaderTests.swift | 2 +- 3 files changed, 369 insertions(+), 40 deletions(-) create mode 100644 Tests/ContainerizationOCITests/BlobResumeTests.swift diff --git a/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift b/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift index 785552690..81b7522f1 100644 --- a/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift +++ b/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift @@ -19,6 +19,7 @@ import ContainerizationError import ContainerizationExtras import Crypto import Foundation +import NIOCore import NIOFoundationCompat #if os(macOS) @@ -146,6 +147,20 @@ extension RegistryClient { name: String, descriptor: Descriptor, closure: (Int64, HTTPClientResponse.Body) async throws -> Void + ) async throws { + try await self.fetchBlob(name: name, descriptor: descriptor, offset: 0) { (expectedBytes, _, body) in + try await closure(expectedBytes, body) + } + } + + /// Fetch a blob from remote registry, requesting bytes from `offset` onward. + /// The closure receives the body's length and the blob offset it starts at, + /// which is 0 if the registry ignored the range. + func fetchBlob( + name: String, + descriptor: Descriptor, + offset: Int64, + closure: (_ length: Int64, _ bodyOffset: Int64, HTTPClientResponse.Body) async throws -> Void ) async throws { var components = base components.path = "/v2/\(name)/blobs/\(descriptor.digest)" @@ -155,12 +170,28 @@ extension RegistryClient { throw ContainerizationError(.invalidArgument, message: "missing media type for descriptor \(descriptor.digest)") } - let headers = [ + var headers = [ ("Accept", mediaType) ] + if offset > 0 { + headers.append(("Range", "bytes=\(offset)-")) + } try await request(components: components, headers: headers) { response in - guard response.status == .ok else { + let bodyOffset: Int64 + switch response.status { + case .ok: + bodyOffset = 0 + case .partialContent where offset > 0: + let contentRange = response.headers.first(name: "Content-Range") + guard let contentRange, contentRange.hasPrefix("bytes \(offset)-") else { + throw ContainerizationError( + .invalidArgument, + message: "unexpected Content-Range \(contentRange ?? "none") for \(descriptor.digest)" + ) + } + bodyOffset = offset + default: let url = components.url?.absoluteString ?? "unknown" let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString throw Error.invalidStatus(url: url, response.status, reason: reason) @@ -171,14 +202,79 @@ extension RegistryClient { throw ContainerizationError(.invalidArgument, message: "missing required header Content-Length") } - guard expectedBytes <= descriptor.size else { + guard bodyOffset + expectedBytes <= descriptor.size else { throw ContainerizationError( .invalidArgument, - message: "declared blob length \(expectedBytes) exceeds descriptor size \(descriptor.size) for \(descriptor.digest)" + message: "declared range end \(bodyOffset + expectedBytes) exceeds descriptor size \(descriptor.size) for \(descriptor.digest)" ) } - try await closure(expectedBytes, response.body) + try await closure(expectedBytes, bodyOffset, response.body) + } + } + + /// Fetch a blob, resuming with a Range request if the connection drops mid-transfer. + /// `closure` is called with the blob's bytes in order, each exactly once, across all attempts. + private func fetchBlobResuming( + name: String, + descriptor: Descriptor, + closure: (ByteBuffer) async throws -> Void + ) async throws -> Int64 { + var received: Int64 = 0 + var retryCount = 0 + while true { + let receivedBeforeAttempt = received + var closureFailed = false + var bodyStarted = false + do { + try await self.fetchBlob(name: name, descriptor: descriptor, offset: received) { (_, bodyOffset, body) in + bodyStarted = true + // Bytes of this body that were already consumed by an earlier attempt. + var skip = received - bodyOffset + for try await var buf in body { + if skip > 0 { + let dropped = min(skip, Int64(buf.readableBytes)) + buf.moveReaderIndex(forwardBy: Int(dropped)) + skip -= dropped + if buf.readableBytes == 0 { + continue + } + } + try Self.validateReceivedSize(received + Int64(buf.readableBytes), descriptor) + do { + try await closure(buf) + } catch { + closureFailed = true + throw error + } + received += Int64(buf.readableBytes) + } + } + return received + } catch { + // `request` already retries failures before the body; only retry a dropped body here. + if !bodyStarted + || closureFailed + || error is ContainerizationError + || error is RegistryClient.Error + || error is CancellationError + { + throw error + } + // The whole blob arrived; the connection dropped after the last byte. + if received == descriptor.size { + return received + } + // Only count consecutive attempts that made no progress. + if received > receivedBeforeAttempt { + retryCount = 0 + } + guard let retryOptions = self.retryOptions, retryCount < retryOptions.maxRetries else { + throw error + } + retryCount += 1 + try await Task.sleep(nanoseconds: retryOptions.retryInterval) + } } } @@ -200,24 +296,19 @@ extension RegistryClient { let handle = try await fs.openFile(forWritingAt: FilePath(file.absolutePath()), options: .newFile(replaceExisting: true)) var writer = handle.bufferedWriter() do { - try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in - var itr = body.makeAsyncIterator() - while let buf = try await itr.next() { - let readBytes = Int64(buf.readableBytes) - received += readBytes - try Self.validateReceivedSize(received, descriptor) - let written = try await writer.write(contentsOf: buf) - await progress?([ - .addSize(written) - ]) - guard written == readBytes else { - throw ContainerizationError( - .internalError, - message: "could not write \(readBytes) bytes to file \(file)" - ) - } - hasher.update(data: buf.readableBytesView) + received = try await self.fetchBlobResuming(name: name, descriptor: descriptor) { buf in + let readBytes = Int64(buf.readableBytes) + let written = try await writer.write(contentsOf: buf) + await progress?([ + .addSize(written) + ]) + guard written == readBytes else { + throw ContainerizationError( + .internalError, + message: "could not write \(readBytes) bytes to file \(file)" + ) } + hasher.update(data: buf.readableBytesView) } try await writer.flush() try await handle.close() @@ -237,26 +328,19 @@ extension RegistryClient { /// Fetch a blob from remote registry and write the contents into a file in the provided directory. public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) { var hasher = SHA256() - var received: Int64 = 0 guard FileManager.default.createFile(atPath: file.path, contents: nil) else { throw ContainerizationError(.internalError, message: "cannot create file at path \(file.path)") } - try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in - let fd = try FileHandle(forWritingTo: file) - defer { - try? fd.close() - } - var itr = body.makeAsyncIterator() - while let buf = try await itr.next() { - let readBytes = Int64(buf.readableBytes) - received += readBytes - try Self.validateReceivedSize(received, descriptor) - await progress?([ - .addSize(readBytes) - ]) - try fd.write(contentsOf: buf.readableBytesView) - hasher.update(data: buf.readableBytesView) - } + let fd = try FileHandle(forWritingTo: file) + defer { + try? fd.close() + } + let received = try await self.fetchBlobResuming(name: name, descriptor: descriptor) { buf in + await progress?([ + .addSize(Int64(buf.readableBytes)) + ]) + try fd.write(contentsOf: buf.readableBytesView) + hasher.update(data: buf.readableBytesView) } let computedDigest = hasher.finalize() return (received, computedDigest) diff --git a/Tests/ContainerizationOCITests/BlobResumeTests.swift b/Tests/ContainerizationOCITests/BlobResumeTests.swift new file mode 100644 index 000000000..6647da704 --- /dev/null +++ b/Tests/ContainerizationOCITests/BlobResumeTests.swift @@ -0,0 +1,245 @@ +//===----------------------------------------------------------------------===// +// Copyright © 2026 Apple Inc. and the Containerization project authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +//===----------------------------------------------------------------------===// + +import ContainerizationError +import Crypto +import Foundation +import NIO +import NIOHTTP1 +import Synchronization +import Testing + +@testable import ContainerizationOCI + +/// Returns the start of a `bytes=-` range header. +private func rangeStart(_ header: String?) -> Int? { + guard let header, header.hasPrefix("bytes="), header.hasSuffix("-") else { + return nil + } + return Int(header.dropFirst("bytes=".count).dropLast()) +} + +/// Serves a blob on loopback, optionally honoring Range, and drops the connection +/// halfway through the body for the first `drops` requests. +private final class BlobStubServer: Sendable { + let port: Int + private let channel: Channel + private let group: MultiThreadedEventLoopGroup + private let shared: Shared + + struct State { + var drops: Int + var rangeHeaders: [String?] = [] + } + + final class Shared: Sendable { + let state: Mutex + + init(_ state: State) { + self.state = Mutex(state) + } + } + + var rangeHeaders: [String?] { + shared.state.withLock { $0.rangeHeaders } + } + + static func start(blob: [UInt8], drops: Int, honorRange: Bool) async throws -> BlobStubServer { + let shared = Shared(State(drops: drops)) + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let bootstrap = ServerBootstrap(group: group) + .serverChannelOption(.backlog, value: 16) + .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) + .childChannelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withPipeliningAssistance: false) + try channel.pipeline.syncOperations.addHandler(Handler(blob: blob, honorRange: honorRange, shared: shared)) + } + } + + do { + let bound = try await bootstrap.bind(host: "127.0.0.1", port: 0).get() + guard let port = bound.localAddress?.port else { + try? await bound.close().get() + throw ContainerizationError(.internalError, message: "stub server bound without a port") + } + return BlobStubServer(port: port, channel: bound, group: group, shared: shared) + } catch { + try? await group.shutdownGracefully() + throw error + } + } + + private init(port: Int, channel: Channel, group: MultiThreadedEventLoopGroup, shared: Shared) { + self.port = port + self.channel = channel + self.group = group + self.shared = shared + } + + func shutdown() async throws { + try? await channel.close().get() + try await group.shutdownGracefully() + } + + private final class Handler: ChannelInboundHandler, @unchecked Sendable { + typealias InboundIn = HTTPServerRequestPart + typealias OutboundOut = HTTPServerResponsePart + + private let blob: [UInt8] + private let honorRange: Bool + private let shared: Shared + private var range: String? + + init(blob: [UInt8], honorRange: Bool, shared: Shared) { + self.blob = blob + self.honorRange = honorRange + self.shared = shared + } + + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + switch unwrapInboundIn(data) { + case .head(let head): + range = head.headers.first(name: "Range") + return + case .body: + return + case .end: + break + } + + let drop = shared.state.withLock { state in + state.rangeHeaders.append(range) + guard state.drops > 0 else { + return false + } + state.drops -= 1 + return true + } + + var start = 0 + var status = HTTPResponseStatus.ok + var headers = HTTPHeaders() + headers.add(name: "Content-Type", value: "application/octet-stream") + if honorRange, let offset = rangeStart(range) { + start = offset + status = .partialContent + headers.add(name: "Content-Range", value: "bytes \(offset)-\(blob.count - 1)/\(blob.count)") + } + headers.add(name: "Content-Length", value: "\(blob.count - start)") + + let head = HTTPResponseHead(version: .http1_1, status: status, headers: headers) + context.write(wrapOutboundOut(.head(head)), promise: nil) + if drop { + // Send half of what was promised, then cut the connection. + let end = start + (blob.count - start) / 2 + let body = context.channel.allocator.buffer(bytes: blob[start.. (digest: SHA256Digest, data: Data, ranges: [String?]) { + let server = try await BlobStubServer.start(blob: Self.blob, drops: drops, honorRange: honorRange) + let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { + try? FileManager.default.removeItem(at: file) + } + let client = RegistryClient(host: "127.0.0.1", scheme: "http", port: server.port, retryOptions: Self.retryOptions) + do { + let (_, digest) = try await client.fetchBlob(name: "test/image", descriptor: Self.descriptor, into: file, progress: nil) + let data = try Data(contentsOf: file) + let ranges = server.rangeHeaders + try await server.shutdown() + return (digest, data, ranges) + } catch { + try? await server.shutdown() + throw error + } + } + + /// The client may receive fewer bytes than the server sent before the connection + /// dropped, so only check that it resumed from somewhere inside the blob. + private func isResume(_ header: String?) -> Bool { + guard let start = rangeStart(header) else { + return false + } + return start > 0 && start < Self.blob.count + } + + @Test func resumesWithRangeAfterDroppedConnection() async throws { + let result = try await fetch(drops: 2, honorRange: true) + #expect(result.digest.digestString == Self.descriptor.digest) + #expect(result.data == Data(Self.blob)) + try #require(result.ranges.count == 3) + #expect(result.ranges[0] == nil) + #expect(result.ranges.dropFirst().allSatisfy(isResume)) + } + + @Test func restartsWhenRegistryIgnoresRange() async throws { + let result = try await fetch(drops: 1, honorRange: false) + #expect(result.digest.digestString == Self.descriptor.digest) + #expect(result.data == Data(Self.blob)) + try #require(result.ranges.count == 2) + #expect(result.ranges[0] == nil) + #expect(isResume(result.ranges[1])) + } + + @Test func failsWithoutRetryOptions() async throws { + let server = try await BlobStubServer.start(blob: Self.blob, drops: 1, honorRange: true) + let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { + try? FileManager.default.removeItem(at: file) + } + let client = RegistryClient(host: "127.0.0.1", scheme: "http", port: server.port) + await #expect(throws: (any Error).self) { + _ = try await client.fetchBlob(name: "test/image", descriptor: Self.descriptor, into: file, progress: nil) + } + #expect(server.rangeHeaders == [nil]) + try await server.shutdown() + } + + @Test func sendsNoRangeWithoutDrops() async throws { + let result = try await fetch(drops: 0, honorRange: true) + #expect(result.data == Data(Self.blob)) + #expect(result.ranges == [nil]) + } +} diff --git a/Tests/ContainerizationOCITests/ResolveDigestHeaderTests.swift b/Tests/ContainerizationOCITests/ResolveDigestHeaderTests.swift index 1ff133314..fe54266d1 100644 --- a/Tests/ContainerizationOCITests/ResolveDigestHeaderTests.swift +++ b/Tests/ContainerizationOCITests/ResolveDigestHeaderTests.swift @@ -25,7 +25,7 @@ import Testing /// `RegistryClient` honours `HTTP_PROXY` from the environment, which would /// divert a request aimed at the in-process stub below. Skip rather than fail /// when a proxy is configured and does not exempt loopback. -private var reachesLoopbackDirectly: Bool { +var reachesLoopbackDirectly: Bool { let env = ProcessInfo.processInfo.environment guard (env["HTTP_PROXY"] ?? env["http_proxy"]) != nil else { return true From 4b81587aba6032b966475a568d6493b8867b2d11 Mon Sep 17 00:00:00 2001 From: Nandan Varma Date: Wed, 2 Dec 2026 22:40:00 -0800 Subject: [PATCH 2/2] Bound blob resumes and require the exact remaining length The declared length must now equal the bytes still missing, so a short or oversized Content-Length fails right away and the check can no longer overflow. Resumes count against maxRetries without resetting, and a 200 reply to a Range request fails instead of downloading the blob again. --- .../Client/RegistryClient+Fetch.swift | 40 +++++----------- .../BlobResumeTests.swift | 47 +++++++++++++++---- 2 files changed, 49 insertions(+), 38 deletions(-) diff --git a/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift b/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift index 81b7522f1..f61ab9b92 100644 --- a/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift +++ b/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift @@ -148,19 +148,15 @@ extension RegistryClient { descriptor: Descriptor, closure: (Int64, HTTPClientResponse.Body) async throws -> Void ) async throws { - try await self.fetchBlob(name: name, descriptor: descriptor, offset: 0) { (expectedBytes, _, body) in - try await closure(expectedBytes, body) - } + try await self.fetchBlob(name: name, descriptor: descriptor, offset: 0, closure: closure) } /// Fetch a blob from remote registry, requesting bytes from `offset` onward. - /// The closure receives the body's length and the blob offset it starts at, - /// which is 0 if the registry ignored the range. func fetchBlob( name: String, descriptor: Descriptor, offset: Int64, - closure: (_ length: Int64, _ bodyOffset: Int64, HTTPClientResponse.Body) async throws -> Void + closure: (Int64, HTTPClientResponse.Body) async throws -> Void ) async throws { var components = base components.path = "/v2/\(name)/blobs/\(descriptor.digest)" @@ -178,10 +174,11 @@ extension RegistryClient { } try await request(components: components, headers: headers) { response in - let bodyOffset: Int64 switch response.status { + case .ok where offset == 0: + break case .ok: - bodyOffset = 0 + throw ContainerizationError(.unsupported, message: "registry ignored the Range request for \(descriptor.digest)") case .partialContent where offset > 0: let contentRange = response.headers.first(name: "Content-Range") guard let contentRange, contentRange.hasPrefix("bytes \(offset)-") else { @@ -190,7 +187,6 @@ extension RegistryClient { message: "unexpected Content-Range \(contentRange ?? "none") for \(descriptor.digest)" ) } - bodyOffset = offset default: let url = components.url?.absoluteString ?? "unknown" let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString @@ -202,14 +198,15 @@ extension RegistryClient { throw ContainerizationError(.invalidArgument, message: "missing required header Content-Length") } - guard bodyOffset + expectedBytes <= descriptor.size else { + let remaining = descriptor.size - offset + guard expectedBytes == remaining else { throw ContainerizationError( .invalidArgument, - message: "declared range end \(bodyOffset + expectedBytes) exceeds descriptor size \(descriptor.size) for \(descriptor.digest)" + message: "declared blob length \(expectedBytes) does not match the \(remaining) remaining bytes of \(descriptor.digest)" ) } - try await closure(expectedBytes, bodyOffset, response.body) + try await closure(expectedBytes, response.body) } } @@ -223,23 +220,12 @@ extension RegistryClient { var received: Int64 = 0 var retryCount = 0 while true { - let receivedBeforeAttempt = received var closureFailed = false var bodyStarted = false do { - try await self.fetchBlob(name: name, descriptor: descriptor, offset: received) { (_, bodyOffset, body) in + try await self.fetchBlob(name: name, descriptor: descriptor, offset: received) { (_, body) in bodyStarted = true - // Bytes of this body that were already consumed by an earlier attempt. - var skip = received - bodyOffset - for try await var buf in body { - if skip > 0 { - let dropped = min(skip, Int64(buf.readableBytes)) - buf.moveReaderIndex(forwardBy: Int(dropped)) - skip -= dropped - if buf.readableBytes == 0 { - continue - } - } + for try await buf in body { try Self.validateReceivedSize(received + Int64(buf.readableBytes), descriptor) do { try await closure(buf) @@ -265,10 +251,6 @@ extension RegistryClient { if received == descriptor.size { return received } - // Only count consecutive attempts that made no progress. - if received > receivedBeforeAttempt { - retryCount = 0 - } guard let retryOptions = self.retryOptions, retryCount < retryOptions.maxRetries else { throw error } diff --git a/Tests/ContainerizationOCITests/BlobResumeTests.swift b/Tests/ContainerizationOCITests/BlobResumeTests.swift index 6647da704..cb19d6b9c 100644 --- a/Tests/ContainerizationOCITests/BlobResumeTests.swift +++ b/Tests/ContainerizationOCITests/BlobResumeTests.swift @@ -33,7 +33,8 @@ private func rangeStart(_ header: String?) -> Int? { } /// Serves a blob on loopback, optionally honoring Range, and drops the connection -/// halfway through the body for the first `drops` requests. +/// halfway through the body for the first `drops` requests. `resumedLength`, if set, +/// replaces the Content-Length of responses to Range requests. private final class BlobStubServer: Sendable { let port: Int private let channel: Channel @@ -57,7 +58,7 @@ private final class BlobStubServer: Sendable { shared.state.withLock { $0.rangeHeaders } } - static func start(blob: [UInt8], drops: Int, honorRange: Bool) async throws -> BlobStubServer { + static func start(blob: [UInt8], drops: Int, honorRange: Bool, resumedLength: String? = nil) async throws -> BlobStubServer { let shared = Shared(State(drops: drops)) let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) let bootstrap = ServerBootstrap(group: group) @@ -66,7 +67,7 @@ private final class BlobStubServer: Sendable { .childChannelInitializer { channel in channel.eventLoop.makeCompletedFuture { try channel.pipeline.syncOperations.configureHTTPServerPipeline(withPipeliningAssistance: false) - try channel.pipeline.syncOperations.addHandler(Handler(blob: blob, honorRange: honorRange, shared: shared)) + try channel.pipeline.syncOperations.addHandler(Handler(blob: blob, honorRange: honorRange, resumedLength: resumedLength, shared: shared)) } } @@ -101,12 +102,14 @@ private final class BlobStubServer: Sendable { private let blob: [UInt8] private let honorRange: Bool + private let resumedLength: String? private let shared: Shared private var range: String? - init(blob: [UInt8], honorRange: Bool, shared: Shared) { + init(blob: [UInt8], honorRange: Bool, resumedLength: String?, shared: Shared) { self.blob = blob self.honorRange = honorRange + self.resumedLength = resumedLength self.shared = shared } @@ -139,7 +142,7 @@ private final class BlobStubServer: Sendable { status = .partialContent headers.add(name: "Content-Range", value: "bytes \(offset)-\(blob.count - 1)/\(blob.count)") } - headers.add(name: "Content-Length", value: "\(blob.count - start)") + headers.add(name: "Content-Length", value: (start > 0 ? resumedLength : nil) ?? "\(blob.count - start)") let head = HTTPResponseHead(version: .http1_1, status: status, headers: headers) context.write(wrapOutboundOut(.head(head)), promise: nil) @@ -214,15 +217,41 @@ struct BlobResumeTests { #expect(result.ranges.dropFirst().allSatisfy(isResume)) } - @Test func restartsWhenRegistryIgnoresRange() async throws { - let result = try await fetch(drops: 1, honorRange: false) - #expect(result.digest.digestString == Self.descriptor.digest) - #expect(result.data == Data(Self.blob)) + /// Runs a fetch that should fail and returns its error and the Range headers the server saw. + private func fetchFailing(drops: Int, honorRange: Bool, resumedLength: String? = nil) async throws -> (error: (any Error)?, ranges: [String?]) { + let server = try await BlobStubServer.start(blob: Self.blob, drops: drops, honorRange: honorRange, resumedLength: resumedLength) + let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { + try? FileManager.default.removeItem(at: file) + } + let client = RegistryClient(host: "127.0.0.1", scheme: "http", port: server.port, retryOptions: Self.retryOptions) + let error = await #expect(throws: (any Error).self) { + _ = try await client.fetchBlob(name: "test/image", descriptor: Self.descriptor, into: file, progress: nil) + } + let ranges = server.rangeHeaders + try await server.shutdown() + return (error, ranges) + } + + @Test func failsWhenRegistryIgnoresRange() async throws { + let result = try await fetchFailing(drops: 1, honorRange: false) + #expect(result.error is ContainerizationError) try #require(result.ranges.count == 2) #expect(result.ranges[0] == nil) #expect(isResume(result.ranges[1])) } + @Test func stopsAfterMaxRetries() async throws { + let result = try await fetchFailing(drops: .max, honorRange: true) + #expect(result.ranges.count == Self.retryOptions.maxRetries + 1) + } + + @Test func rejectsOverflowingLengthOnResume() async throws { + let result = try await fetchFailing(drops: 1, honorRange: true, resumedLength: "\(Int64.max)") + #expect(result.error is ContainerizationError) + #expect(result.ranges.count == 2) + } + @Test func failsWithoutRetryOptions() async throws { let server = try await BlobStubServer.start(blob: Self.blob, drops: 1, honorRange: true) let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)