Skip to content

fix: add check to drop events that return a 400 response from Segment #296

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

Merged
merged 5 commits into from
Feb 13, 2024
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
6 changes: 6 additions & 0 deletions Sources/Segment/Plugins/SegmentDestination.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,12 @@ public class SegmentDestination: DestinationPlugin, Subscriber, FlushCompletion
case .success(_):
storage.remove(file: url)
self.cleanupUploads()

// we don't want to retry events in a given batch when a 400
// response for malformed JSON is returned
case .failure(Segment.HTTPClientErrors.statusCode(code: 400)):
storage.remove(file: url)
self.cleanupUploads()
default:
break
}
Expand Down
52 changes: 52 additions & 0 deletions Tests/Segment-Tests/Analytics_Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -865,4 +865,56 @@ final class Analytics_Tests: XCTestCase {
let d: Double? = trackEvent?.properties?.value(forKeyPath: "TestNaN")
XCTAssertNil(d)
}

// Linux doesn't know what URLProtocol is and on watchOS it somehow works differently and isn't hit.
#if !os(Linux) && !os(watchOS)
func testFailedSegmentResponse() throws {
//register our network blocker (returns 400 response)
guard URLProtocol.registerClass(FailedNetworkCalls.self) else {
XCTFail(); return }

let analytics = Analytics(configuration: Configuration(writeKey: "networkTest"))

waitUntilStarted(analytics: analytics)

//set the httpClient to use our blocker session
let segment = analytics.find(pluginType: SegmentDestination.self)
let configuration = URLSessionConfiguration.ephemeral
configuration.allowsCellularAccess = true
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForRequest = 60
configuration.httpMaximumConnectionsPerHost = 2
configuration.protocolClasses = [FailedNetworkCalls.self]
configuration.httpAdditionalHeaders = [
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic test",
"User-Agent": "analytics-ios/\(Analytics.version())"
]

let blockSession = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)

segment?.httpClient?.session = blockSession

analytics.track(name: "test track", properties: ["Malformed Paylod": "My Failed Prop"])

//get fileUrl from track call
let storedEvents: [URL]? = analytics.storage.read(.events)
let fileURL = storedEvents![0]


let expectation = XCTestExpectation()

analytics.flush {
expectation.fulfill()
}

wait(for: [expectation], timeout: 1.0)

let newStoredEvents: [URL]? = analytics.storage.read(.events)

XCTAssert(!(newStoredEvents?.contains(fileURL))!)

XCTAssertFalse(FileManager.default.fileExists(atPath: fileURL.path))
}
#endif
}
23 changes: 23 additions & 0 deletions Tests/Segment-Tests/Support/TestUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,27 @@ class BlockNetworkCalls: URLProtocol {
}
}

class FailedNetworkCalls: URLProtocol {
var initialURL: URL? = nil
override class func canInit(with request: URLRequest) -> Bool {

return true
}

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}

override var cachedResponse: CachedURLResponse? { return nil }

override func startLoading() {
client?.urlProtocol(self, didReceive: HTTPURLResponse(url: URL(string: "http://api.segment.com")!, statusCode: 400, httpVersion: nil, headerFields: ["blocked": "true"])!, cacheStoragePolicy: .notAllowed)
client?.urlProtocolDidFinishLoading(self)
}

override func stopLoading() {

}
}

#endif