Skip to content

Commit

Permalink
fix: Fail requests when encoding request body fails.
Browse files Browse the repository at this point in the history
  • Loading branch information
crleona committed Aug 20, 2024
1 parent 056ccbf commit 79a51c2
Show file tree
Hide file tree
Showing 9 changed files with 47 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ class TestStorage: Storage {
configuration: Configuration,
eventPipeline: EventPipeline,
eventBlock: URL,
eventsString: String
eventsString: String,
logger: (any Logger)?
) -> ResponseHandler {
class TestResponseHandler: ResponseHandler {

Expand Down
3 changes: 2 additions & 1 deletion Sources/Amplitude/Storages/InMemoryStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ class InMemoryStorage: Storage {
configuration: Configuration,
eventPipeline: EventPipeline,
eventBlock: EventBlock,
eventsString: String
eventsString: String,
logger: (any Logger)?
) -> ResponseHandler {
abort()
}
Expand Down
6 changes: 4 additions & 2 deletions Sources/Amplitude/Storages/PersistentStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,16 @@ class PersistentStorage: Storage {
configuration: Configuration,
eventPipeline: EventPipeline,
eventBlock: EventBlock,
eventsString: String
eventsString: String,
logger: (any Logger)?
) -> ResponseHandler {
return PersistentStorageResponseHandler(
configuration: configuration,
storage: self,
eventPipeline: eventPipeline,
eventBlock: eventBlock,
eventsString: eventsString
eventsString: eventsString,
logger: logger
)
}

Expand Down
3 changes: 2 additions & 1 deletion Sources/Amplitude/Types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ public protocol Storage {
configuration: Configuration,
eventPipeline: EventPipeline,
eventBlock: URL,
eventsString: String
eventsString: String,
logger: (any Logger)?
) -> ResponseHandler
}

Expand Down
3 changes: 2 additions & 1 deletion Sources/Amplitude/Utilities/EventPipeline.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ public class EventPipeline {
configuration: self.configuration,
eventPipeline: self,
eventBlock: eventFile,
eventsString: eventsString
eventsString: eventsString,
logger: logger
)
responseHandler.handle(result: result)
self.completeUpload(for: eventFile)
Expand Down
17 changes: 12 additions & 5 deletions Sources/Amplitude/Utilities/HttpClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ class HttpClient {
let backgroundTaskCompletion = VendorSystem.current.beginBackgroundTask()
do {
let request = try getRequest()
let requestData = getRequestData(events: events)
// Attempt to generate requestData without diagnostics in case diagnostics are causing a failure.
let requestData = getRequestData(events: events) ?? getRequestData(events: events, includeDiagnostics: false)
guard let requestData = requestData else {
throw Exception.invalidRequestData
}

sessionTask = session.uploadTask(with: request, from: requestData) { [callbackQueue, configuration] data, response, error in
callbackQueue.async {
Expand Down Expand Up @@ -63,8 +67,10 @@ class HttpClient {
}
sessionTask!.resume()
} catch {
completion(.failure(Exception.httpError(code: 500, data: nil)))
backgroundTaskCompletion?()
callbackQueue.async {
completion(.failure(Exception.httpError(code: 500, data: nil)))
backgroundTaskCompletion?()
}
}
return sessionTask
}
Expand Down Expand Up @@ -103,7 +109,7 @@ class HttpClient {
return request
}

func getRequestData(events: String) -> Data? {
func getRequestData(events: String, includeDiagnostics: Bool = true) -> Data? {
let apiKey = configuration.apiKey
let clientUploadTime: String = dateFormatter.string(from: getDate())
var requestPayload = """
Expand All @@ -114,7 +120,7 @@ class HttpClient {
,"options":{"min_id_length":\(minIdLength)}
"""
}
if diagnostics.hasDiagnostics() {
if includeDiagnostics, diagnostics.hasDiagnostics() {
let diagnosticsInfo = diagnostics.extractDiagonosticsToString()
if !diagnosticsInfo.isEmpty {
requestPayload += """
Expand Down Expand Up @@ -144,5 +150,6 @@ extension HttpClient {
enum Exception: Error {
case invalidUrl(url: String)
case httpError(code: Int, data: Data?)
case invalidRequestData
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,22 @@ class PersistentStorageResponseHandler: ResponseHandler {
var eventPipeline: EventPipeline
var eventBlock: URL
var eventsString: String
private let logger: (any Logger)?

init(
configuration: Configuration,
storage: PersistentStorage,
eventPipeline: EventPipeline,
eventBlock: URL,
eventsString: String
eventsString: String,
logger: (any Logger)?
) {
self.configuration = configuration
self.storage = storage
self.eventPipeline = eventPipeline
self.eventBlock = eventBlock
self.eventsString = eventsString
self.logger = logger
}

func handleSuccessResponse(code: Int) {
Expand Down Expand Up @@ -123,6 +126,11 @@ class PersistentStorageResponseHandler: ResponseHandler {
// wait for next time to try again
}

func handleInvalidDataResponse() {
logger?.error(message: "Unable to construct a request from block \(eventBlock), deleting...")
storage.remove(eventBlock: eventBlock)
}

func handle(result: Result<Int, Error>) {
switch result {
case .success(let code):
Expand All @@ -149,6 +157,8 @@ class PersistentStorageResponseHandler: ResponseHandler {
default:
handleFailedResponse(data: json)
}
case HttpClient.Exception.invalidRequestData:
handleInvalidDataResponse()
default:
break
}
Expand Down
3 changes: 2 additions & 1 deletion Tests/AmplitudeTests/Supports/TestUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ class FakeInMemoryStorage: Storage {
configuration: Configuration,
eventPipeline: EventPipeline,
eventBlock: EventBlock,
eventsString: String
eventsString: String,
logger: (any Logger)?
) -> ResponseHandler {
FakeResponseHandler(
configuration: configuration, storage: self, eventPipeline: eventPipeline, eventBlock: eventBlock,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ final class PersistentStorageResponseHandlerTests: XCTestCase {
storage: storage,
eventPipeline: eventPipeline,
eventBlock: eventBlock,
eventsString: eventsString
eventsString: eventsString,
logger: nil
)

XCTAssertEqual(handler.eventsString, eventsString)
Expand All @@ -58,7 +59,8 @@ final class PersistentStorageResponseHandlerTests: XCTestCase {
storage: fakePersistentStorage,
eventPipeline: eventPipeline,
eventBlock: eventBlock,
eventsString: eventsString
eventsString: eventsString,
logger: nil
)

handler.removeEventCallbackByEventsString(eventsString: eventsString)
Expand Down Expand Up @@ -91,7 +93,8 @@ final class PersistentStorageResponseHandlerTests: XCTestCase {
storage: fakePersistentStorage,
eventPipeline: eventPipeline,
eventBlock: eventBlock,
eventsString: eventsString
eventsString: eventsString,
logger: nil
)

handler.removeEventCallbackByEventsString(eventsString: eventsString)
Expand All @@ -116,7 +119,8 @@ final class PersistentStorageResponseHandlerTests: XCTestCase {
storage: fakePersistentStorage,
eventPipeline: eventPipeline,
eventBlock: eventBlock,
eventsString: eventsString
eventsString: eventsString,
logger: nil
)

handler.handleSuccessResponse(code: 200)
Expand Down Expand Up @@ -147,7 +151,8 @@ final class PersistentStorageResponseHandlerTests: XCTestCase {
storage: fakePersistentStorage,
eventPipeline: eventPipeline,
eventBlock: eventBlock,
eventsString: eventsString
eventsString: eventsString,
logger: nil
)

handler.handleBadRequestResponse(data: ["error": "Invalid API key: \(configuration.apiKey)"])
Expand Down

0 comments on commit 79a51c2

Please sign in to comment.