Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FIX] Upload manager adjustments #48

Merged
merged 1 commit into from
Aug 21, 2023
Merged
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
170 changes: 100 additions & 70 deletions Sources/Networking/Core/Upload/UploadAPIManager.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//
// UploadAPIManager.swift
//
//
//
// Created by Tony Ngo on 12.06.2023.
//
Expand Down Expand Up @@ -59,6 +59,38 @@ open class UploadAPIManager: NSObject {
}
}

// MARK: URLSessionDataDelegate
extension UploadAPIManager: URLSessionDataDelegate {
public func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive data: Data
) {
Task {
guard let uploadTask = await uploadTask(for: dataTask) else {
return
}

if let originalRequest = dataTask.originalRequest,
let response = dataTask.response {
do {
try await handleUploadTaskCompletion(
uploadTask: uploadTask,
urlRequest: originalRequest,
response: response,
data: data
)
} catch {
await handleUploadTaskError(
uploadTask: uploadTask,
error: error
)
}
}
}
}
}

// MARK: - URLSessionTaskDelegate
extension UploadAPIManager: URLSessionTaskDelegate {
public func urlSession(
Expand All @@ -74,6 +106,27 @@ extension UploadAPIManager: URLSessionTaskDelegate {
.send(UploadTask.State(task: task))
}
}

public func urlSession(
_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?
) {
Task {
await uploadTask(for: task)?
.statePublisher
.send(UploadTask.State(task: task))

guard let uploadTask = await uploadTask(for: task) else {
return
}

await handleUploadTaskError(
uploadTask: uploadTask,
error: error
)
}
}
}

// MARK: - UploadAPIManaging
Expand Down Expand Up @@ -119,10 +172,13 @@ extension UploadAPIManager: UploadAPIManaging {
retryConfiguration: RetryConfiguration?
) async throws -> UploadTask {
let endpointRequest = EndpointRequest(endpoint, sessionId: sessionId)

// Determine if the session configuration is background.
let usesBackgroundSession = urlSessionConfiguration.sessionSendsLaunchEvents

// Encode in-memory and upload directly if the payload's size is less than the threshold,
// otherwise we write the payload to the disk first and upload by reading the file content.
if multipartFormData.size < sizeThreshold {
if multipartFormData.size < sizeThreshold && !usesBackgroundSession {
let encodedMultipartFormData = try multipartFormDataEncoder.encode(multipartFormData)
return try await uploadRequest(
.data(encodedMultipartFormData),
Expand Down Expand Up @@ -180,30 +236,22 @@ private extension UploadAPIManager {
) async throws -> UploadTask {
do {
let urlRequest = try await prepare(request)

let sessionUploadTask = sessionUploadTask(
with: uploadable,
for: urlRequest
) { [weak self] data, response, error in
self?.handleUploadTaskCompletion(
urlRequest: urlRequest,
endpointRequest: request,
retryConfiguration: retryConfiguration,
data: data,
response: response,
error: error
)
}

)

let uploadTask = await existingUploadTaskOrNew(
for: sessionUploadTask,
request: request,
uploadable: uploadable
)

// Store the task for future processing
await uploadTasks.set(value: uploadTask, for: request.id)
sessionUploadTask.resume()

return uploadTask
} catch {
throw await errorProcessors.process(error, for: request)
Expand All @@ -229,59 +277,44 @@ private extension UploadAPIManager {
}

func handleUploadTaskCompletion(
uploadTask: UploadTask,
urlRequest: URLRequest,
endpointRequest: EndpointRequest,
retryConfiguration: RetryConfiguration?,
data: Data?,
response: URLResponse?,
response: URLResponse,
data: Data
) async throws {
var state = UploadTask.State(task: uploadTask.task)
state.response = try await responseProcessors.process(
(data, response),
with: urlRequest,
for: uploadTask.endpointRequest
)
await uploadTask.complete(with: state)

// Cleanup on successful task completion
await uploadTask.resetRetryCounter()
await uploadTasks.set(value: nil, for: uploadTask.endpointRequest.id)
}

func handleUploadTaskError(
uploadTask: UploadTask,
error: Error?
) {
Task {
guard let uploadTask = await uploadTasks.getValue(for: endpointRequest.id) else {
) async {
var state = UploadTask.State(task: uploadTask.task)

if let error {
// URLError.Code.cancelled is thrown if the URLSessionTask is cancelled.
// Consider this action intentional, thus the request won't be retried.
guard !state.cancelled else {
return
}

var state = UploadTask.State(task: uploadTask.task)
if let data, let response {
state.response = try await responseProcessors.process(
(data, response),
with: urlRequest,
for: endpointRequest
)

try await uploadTask.complete(with: state)

// Cleanup on successful task completion
await uploadTask.cleanup()
await uploadTasks.set(value: nil, for: endpointRequest.id)
} else if let error {
do {
// URLError.Code.cancelled is thrown if the URLSessionTask is cancelled.
// Consider this action intentional, thus the request won't be retried.
guard !state.cancelled else {
throw error
}

try await uploadTask.sleepIfRetry(
for: error,
retryConfiguration: retryConfiguration
)

try await self.uploadRequest(
uploadTask.uploadable,
request: uploadTask.endpointRequest,
retryConfiguration: retryConfiguration
)
} catch {
state.error = await errorProcessors.process(
error,
for: uploadTask.endpointRequest
)

// No cleanup in case the task will be retried.
try await uploadTask.complete(with: state)
}
}

state.error = await errorProcessors.process(
error,
for: uploadTask.endpointRequest
)

// No cleanup in case the task will be retried.
await uploadTask.complete(with: state)
}
}

Expand All @@ -294,21 +327,18 @@ private extension UploadAPIManager {
/// - We'll need to handle errors and responses from the request using delegates.
func sessionUploadTask(
with uploadable: Uploadable,
for request: URLRequest,
completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void
for request: URLRequest
) -> URLSessionUploadTask {
switch uploadable {
case let .data(data):
return urlSession.uploadTask(
with: request,
from: data,
completionHandler: completionHandler
from: data
)
case let .file(fileUrl, _):
return urlSession.uploadTask(
with: request,
fromFile: fileUrl,
completionHandler: completionHandler
fromFile: fileUrl
)
}
}
Expand Down
5 changes: 2 additions & 3 deletions Sources/Networking/Core/Upload/UploadTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,13 @@ extension UploadTask {
/// - Parameters:
/// - state: The latest state to emit before completing the task.
/// - delay: The delay between the emitting the `state` and completion in nanoseconds. Defaults to 0.2 seconds.
func complete(with state: State, delay: TimeInterval = 20_000_000) async throws {
func complete(with state: State, delay: TimeInterval = 20_000_000) async {
statePublisher.send(state)

// Publishing value and completion one after another might cause the completion
// cancelling the whole stream before the client can process the emitted value.
try await Task.sleep(nanoseconds: UInt64(delay))
try? await Task.sleep(nanoseconds: UInt64(delay))
statePublisher.send(completion: .finished)

}

func cleanup() async {
Expand Down