Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Sources/Nuke/Pipeline/ImagePipeline+Delegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ extension ImagePipeline {
@ImagePipelineActor
func willLoadData(for request: ImageRequest, urlRequest: URLRequest, pipeline: ImagePipeline) async throws -> URLRequest

/// Observes an encoded-data buffer operation before Nuke reserves or appends.
///
/// Called synchronously on `ImagePipelineActor`, once per underlying data fetch
/// rather than per coalesced image-task subscriber. Return quickly and sample
/// before collecting expensive metrics. No body bytes are exposed. An append
/// reports logical byte counts, not allocator capacity.
@ImagePipelineActor
func willUpdateDataBuffer(for request: ImageRequest, context: ImagePipeline.DataBufferUpdateContext, pipeline: ImagePipeline)

// MARK: Caching

/// Returns in-memory image cache for the given request. Return `nil` to prevent cache reads and writes.
Expand Down Expand Up @@ -140,6 +149,9 @@ extension ImagePipeline.Delegate {
urlRequest
}

@ImagePipelineActor
public func willUpdateDataBuffer(for request: ImageRequest, context: ImagePipeline.DataBufferUpdateContext, pipeline: ImagePipeline) {}

public func dataCache(for request: ImageRequest, pipeline: ImagePipeline) -> (any DataCaching)? {
pipeline.configuration.dataCache
}
Expand Down Expand Up @@ -235,3 +247,24 @@ extension ImagePipeline {
}

final class ImagePipelineDefaultDelegate: ImagePipeline.Delegate {}

extension ImagePipeline {
/// Metadata for an upcoming encoded-data buffer operation; does not retain body bytes.
public struct DataBufferUpdateContext: Sendable {
public enum Operation: Sendable {
case initialReservation
case resumedReservation
case append
}

public let operation: Operation
/// Logical bytes held before the operation, not physical allocation capacity.
public let bufferedByteCount: Int
/// Bytes being appended; zero for a reservation of an existing buffer.
public let incomingByteCount: Int
/// The argument to reserveCapacity; absent for append because Data hides capacity.
public let requestedCapacity: Int?
/// expectedContentLength is the remaining body length for a resumed HTTP response.
public let response: URLResponse
}
}
29 changes: 27 additions & 2 deletions Sources/Nuke/Tasks/TaskFetchOriginalData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,9 @@ final class TaskFetchOriginalData: AsyncPipelineTask<(Data, URLResponse?)> {
}
}
if resumedDataCount > 0, expectedSize > 0 {
data.reserveCapacity(Int(min(expectedSize, maximumReservedCapacity)))
let capacity = Int(min(expectedSize, maximumReservedCapacity))
reportDataBufferUpdate(.resumedReservation, response: response, requestedCapacity: capacity)
data.reserveCapacity(capacity)
}
}

Expand All @@ -257,9 +259,12 @@ final class TaskFetchOriginalData: AsyncPipelineTask<(Data, URLResponse?)> {
if data.isEmpty {
data = chunk
if response.expectedContentLength > chunk.count {
data.reserveCapacity(Int(min(response.expectedContentLength, maximumReservedCapacity)))
let capacity = Int(min(response.expectedContentLength, maximumReservedCapacity))
reportDataBufferUpdate(.initialReservation, response: response, requestedCapacity: capacity)
data.reserveCapacity(capacity)
}
} else {
reportDataBufferUpdate(.append, response: response, incomingByteCount: chunk.count)
data.append(chunk)
}
urlResponse = response
Expand All @@ -278,6 +283,26 @@ final class TaskFetchOriginalData: AsyncPipelineTask<(Data, URLResponse?)> {
send(value: (data, response))
}

private func reportDataBufferUpdate(
_ operation: ImagePipeline.DataBufferUpdateContext.Operation,
response: URLResponse,
incomingByteCount: Int = 0,
requestedCapacity: Int? = nil
) {
guard !pipeline.isDefaultDelegate else { return }
pipeline.delegate.willUpdateDataBuffer(
for: request,
context: .init(
operation: operation,
bufferedByteCount: data.count,
incomingByteCount: incomingByteCount,
requestedCapacity: requestedCapacity,
response: response
),
pipeline: pipeline
)
}

private func dataTaskDidFinish(error: ImagePipeline.Error? = nil) {
guard !isDisposed else { return }

Expand Down
122 changes: 122 additions & 0 deletions Tests/NukeTests/ImagePipelineTests/ImagePipelineDataBufferTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// The MIT License (MIT)
//
// Copyright (c) 2015-2026 Alexander Grebenyuk (github.com/kean).

import Testing
import Foundation
@testable import Nuke

@Suite(.timeLimit(.minutes(5)))
struct ImagePipelineDataBufferTests {
@Test(arguments: [12288, -1])
func reportsLogicalBytesWithoutChangingTheBody(expectedLength: Int) async throws {
let body = Data(repeating: 7, count: 12288)
let loader = MockDataLoader()
loader.results[Test.url] = .success((body, URLResponse(url: Test.url, mimeType: "image/jpeg", expectedContentLength: expectedLength, textEncodingName: nil)))
let delegate = await BufferDelegate()
let pipeline = ImagePipeline(delegate: delegate) {
$0.dataLoader = loader
$0.imageCache = nil
}

let (data, _) = try await pipeline.data(for: Test.request)

#expect(data == body)
let updates = await delegate.updates
#expect(updates.count == (expectedLength > 0 ? 2 : 1))
if expectedLength > 0 {
let reservation = try #require(updates.first)
#expect(reservation.operation == .initialReservation)
#expect(reservation.bufferedByteCount == 6144)
#expect(reservation.incomingByteCount == 0)
#expect(reservation.requestedCapacity == expectedLength)
}
let append = try #require(updates.last)
#expect(append.operation == .append)
#expect(append.bufferedByteCount == 6144)
#expect(append.incomingByteCount == 6144)
#expect(append.requestedCapacity == nil)
#expect(append.response.expectedContentLength == Int64(expectedLength))
#expect(append.response.mimeType == "image/jpeg")
}

@Test func singleChunkDoesNotReportAnAllocation() async throws {
let delegate = await BufferDelegate()
let pipeline = ImagePipeline(delegate: delegate) {
$0.dataLoader = MockDataLoader()
$0.imageCache = nil
}

let (data, _) = try await pipeline.data(for: Test.request)

#expect(data == Test.data)
#expect(await delegate.updates.isEmpty)
}

@Test func sizeRejectionPrecedesTheReservationHook() async throws {
let loader = MockDataLoader()
loader.results[Test.url] = .success((Test.data, URLResponse(url: Test.url, mimeType: nil, expectedContentLength: Test.data.count, textEncodingName: nil)))
let delegate = await BufferDelegate()
let pipeline = ImagePipeline(delegate: delegate) {
$0.dataLoader = loader
$0.imageCache = nil
$0.maximumResponseDataSize = 100
}

await #expect(throws: ImagePipeline.Error.dataDownloadExceededMaximumSize) {
try await pipeline.data(for: Test.request)
}
#expect(await delegate.updates.isEmpty)
}

@Test func resumedReservationIncludesThePrefix() async throws {
let server = MockRangeServer(data: Test.data, validator: ["ETag": "\"v1\""])
server.steps = [.fail(after: 10000), .serve]
let delegate = await BufferDelegate()
let pipeline = ImagePipeline(delegate: delegate) {
$0.dataLoader = server
$0.imageCache = nil
}
_ = try? await pipeline.data(for: Test.request)
await delegate.reset()

let (data, _) = try await pipeline.data(for: Test.request)

#expect(data == Test.data)
#expect(server.requests.last?.value(forHTTPHeaderField: "Range") == "bytes=10000-")
let updates = await delegate.updates
let reservation = try #require(updates.first)
#expect(reservation.operation == .resumedReservation)
#expect(reservation.bufferedByteCount == 10000)
#expect(reservation.incomingByteCount == 0)
#expect(reservation.requestedCapacity == Test.data.count)
#expect(reservation.response.expectedContentLength == Int64(Test.data.count - 10000))
#expect(updates.dropFirst().allSatisfy { $0.operation == .append && $0.requestedCapacity == nil })
}

@Test func defaultDelegateStillReturnsTheCompleteBody() async throws {
let loader = MockDataLoader()
loader.results[Test.url] = .success((Test.data, URLResponse(url: Test.url, mimeType: nil, expectedContentLength: Test.data.count, textEncodingName: nil)))
let pipeline = ImagePipeline {
$0.dataLoader = loader
$0.imageCache = nil
}

let (data, _) = try await pipeline.data(for: Test.request)

#expect(data == Test.data)
}
}

@ImagePipelineActor
private final class BufferDelegate: ImagePipeline.Delegate {
var updates: [ImagePipeline.DataBufferUpdateContext] = []

func willUpdateDataBuffer(for request: ImageRequest, context: ImagePipeline.DataBufferUpdateContext, pipeline: ImagePipeline) {
updates.append(context)
}

func reset() {
updates.removeAll()
}
}