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

Add additional timing metrics #1346

Merged
merged 8 commits into from
Jun 26, 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## unreleased
* BraintreeCore
* For analytics, only call `fetchOrReturnRemoteConfig()` when batch uploading, not on each analytic event enqueue
* For analytics, add additional metrics on networking timing

## 6.21.0 (2024-06-12)
* BraintreePayPal
Expand Down
1 change: 0 additions & 1 deletion Demo/Application/Base/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ import BraintreeCore
if let preferences = settings.object(forKey: "PreferenceSpecifiers") as? Array<[String: Any]> {
var defaultsToRegister: [String: Any] = [:]
preferences.forEach { prefSpecification in
print(prefSpecification)
if let key = prefSpecification["Key"] as? String, prefSpecification.keys.contains("DefaultValue") {
defaultsToRegister[key] = prefSpecification["DefaultValue"]
}
Expand Down
25 changes: 18 additions & 7 deletions Demo/Application/Features/PayPalWebCheckoutViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,28 @@ class PayPalWebCheckoutViewController: PaymentButtonBaseViewController {
let payPalCheckoutButton = createButton(title: "PayPal Checkout", action: #selector(tappedPayPalCheckout))
let payPalVaultButton = createButton(title: "PayPal Vault", action: #selector(tappedPayPalVault))
let payPalAppSwitchButton = createButton(title: "PayPal App Switch", action: #selector(tappedPayPalAppSwitch))
let oneTimeCheckoutStackView = buttonsStackView(label: "1-Time Checkout", views: [
UIStackView(arrangedSubviews: [payLaterToggleLabel, payLaterToggle]),
UIStackView(arrangedSubviews: [newPayPalCheckoutToggleLabel, newPayPalCheckoutToggle]),
payPalCheckoutButton
])
let vaultStackView = buttonsStackView(label: "Vault",views: [payPalVaultButton, payPalAppSwitchButton])


let stackView = UIStackView(arrangedSubviews: [
UIStackView(arrangedSubviews: [emailLabel, emailTextField]),
buttonsStackView(label: "1-Time Checkout", views: [
UIStackView(arrangedSubviews: [payLaterToggleLabel, payLaterToggle]),
UIStackView(arrangedSubviews: [newPayPalCheckoutToggleLabel, newPayPalCheckoutToggle]),
payPalCheckoutButton
]),
buttonsStackView(label: "Vault",views: [payPalVaultButton, payPalAppSwitchButton])
oneTimeCheckoutStackView,
vaultStackView
])


NSLayoutConstraint.activate([
oneTimeCheckoutStackView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor),
oneTimeCheckoutStackView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor),

vaultStackView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor),
vaultStackView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor)
])

stackView.axis = .vertical
stackView.distribution = .fillProportionally
stackView.spacing = 25
Expand Down
8 changes: 8 additions & 0 deletions Sources/BraintreeCore/Analytics/BTAnalyticsService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,25 +51,29 @@ class BTAnalyticsService: Equatable {
/// - startTime: Optional. The start time of the networking request.
func sendAnalyticsEvent(
_ eventName: String,
connectionStartTime: Int? = nil,
correlationID: String? = nil,
endpoint: String? = nil,
endTime: Int? = nil,
errorDescription: String? = nil,
isVaultRequest: Bool? = nil,
linkType: String? = nil,
payPalContextID: String? = nil,
requestStartTime: Int? = nil,
startTime: Int? = nil
) {
Task(priority: .background) {
await performEventRequest(
eventName,
connectionStartTime: connectionStartTime,
correlationID: correlationID,
endpoint: endpoint,
endTime: endTime,
errorDescription: errorDescription,
isVaultRequest: isVaultRequest,
linkType: linkType,
payPalContextID: payPalContextID,
requestStartTime: requestStartTime,
startTime: startTime
)
}
Expand All @@ -78,17 +82,20 @@ class BTAnalyticsService: Equatable {
/// Exposed to be able to execute this function synchronously in unit tests
func performEventRequest(
_ eventName: String,
connectionStartTime: Int? = nil,
correlationID: String? = nil,
endpoint: String? = nil,
endTime: Int? = nil,
errorDescription: String? = nil,
isVaultRequest: Bool? = nil,
linkType: String? = nil,
payPalContextID: String? = nil,
requestStartTime: Int? = nil,
startTime: Int? = nil
) async {
let timestampInMilliseconds = Date().utcTimestampMilliseconds
let event = FPTIBatchData.Event(
connectionStartTime: connectionStartTime,
correlationID: correlationID,
endpoint: endpoint,
endTime: endTime,
Expand All @@ -97,6 +104,7 @@ class BTAnalyticsService: Equatable {
isVaultRequest: isVaultRequest,
linkType: linkType,
payPalContextID: payPalContextID,
requestStartTime: requestStartTime,
startTime: startTime,
timestamp: String(timestampInMilliseconds)
)
Expand Down
10 changes: 10 additions & 0 deletions Sources/BraintreeCore/Analytics/FPTIBatchData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,13 @@ struct FPTIBatchData: Codable {

static var application: URLOpener = UIApplication.shared

/// UTC millisecond timestamp when a networking task started establishing a TCP connection. See [Apple's docs](https://developer.apple.com/documentation/foundation/urlsessiontasktransactionmetrics#3162615).
///
/// `nil` if a persistent connection is used.
let connectionStartTime: Int?
let correlationID: String?
let endpoint: String?
/// UTC millisecond timestamp when a networking task completed.
let endTime: Int?
let errorDescription: String?
let eventName: String
Expand All @@ -41,19 +46,24 @@ struct FPTIBatchData: Codable {
/// This value will be PayPal Order ID, Payment Token, EC token, Billing Agreement, or Venmo Context ID depending on the flow
let payPalContextID: String?
let payPalInstalled: Bool = application.isPayPalAppInstalled()
/// UTC millisecond timestamp when a networking task started requesting a resource. See [Apple's docs](https://developer.apple.com/documentation/foundation/urlsessiontasktransactionmetrics#3162615).
let requestStartTime: Int?
/// UTC millisecond timestamp when a networking task initiated.
let startTime: Int?
let timestamp: String
let tenantName: String = "Braintree"
let venmoInstalled: Bool = application.isVenmoAppInstalled()

enum CodingKeys: String, CodingKey {
case connectionStartTime = "connect_start_time"
case correlationID = "correlation_id"
case errorDescription = "error_desc"
case eventName = "event_name"
case isVaultRequest = "is_vault"
case linkType = "link_type"
case payPalContextID = "paypal_context_id"
case payPalInstalled = "paypal_installed"
case requestStartTime = "request_start_time"
case timestamp = "t"
case tenantName = "tenant_name"
case startTime = "start_time"
Expand Down
4 changes: 3 additions & 1 deletion Sources/BraintreeCore/BTAPIClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -424,14 +424,16 @@ import Foundation

// MARK: BTAPITimingDelegate conformance

func fetchAPITiming(path: String, startTime: Int, endTime: Int) {
func fetchAPITiming(path: String, connectionStartTime: Int?, requestStartTime: Int?, startTime: Int, endTime: Int) {
let cleanedPath = path.replacingOccurrences(of: "/merchants/([A-Za-z0-9]+)/client_api", with: "", options: .regularExpression)

if cleanedPath != "/v1/tracking/batch/events" {
analyticsService?.sendAnalyticsEvent(
BTCoreAnalytics.apiRequestLatency,
connectionStartTime: connectionStartTime,
endpoint: cleanedPath,
endTime: endTime,
requestStartTime: requestStartTime,
startTime: startTime
)
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/BraintreeCore/BTAPITimingDelegate.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Foundation

protocol BTHTTPNetworkTiming: AnyObject {
func fetchAPITiming(path: String, startTime: Int, endTime: Int)
func fetchAPITiming(path: String, connectionStartTime: Int?, requestStartTime: Int?, startTime: Int, endTime: Int)
}
2 changes: 2 additions & 0 deletions Sources/BraintreeCore/BTHTTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,8 @@ class BTHTTP: NSObject, URLSessionTaskDelegate {
let path = transaction.request.url?.path {
networkTimingDelegate?.fetchAPITiming(
path: path,
connectionStartTime: transaction.connectStartDate?.utcTimestampMilliseconds,
requestStartTime: transaction.requestStartDate?.utcTimestampMilliseconds,
startTime: startDate.utcTimestampMilliseconds,
endTime: endDate.utcTimestampMilliseconds
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ final class FPTIBatchData_Tests: XCTestCase {

let eventParams = [
FPTIBatchData.Event(
connectionStartTime: 123,
correlationID: "fake-correlation-id-1",
endpoint: "/v1/paypal_hermes/setup_billing_agreement",
endTime: 111222333444555,
Expand All @@ -25,10 +26,12 @@ final class FPTIBatchData_Tests: XCTestCase {
isVaultRequest: false,
linkType: "universal",
payPalContextID: "fake-order-id",
requestStartTime: 456,
startTime: 999888777666,
timestamp: "fake-time-1"
),
FPTIBatchData.Event(
connectionStartTime: nil,
correlationID: nil,
endpoint: nil,
endTime: nil,
Expand All @@ -37,6 +40,7 @@ final class FPTIBatchData_Tests: XCTestCase {
isVaultRequest: true,
linkType: nil,
payPalContextID: "fake-order-id-2",
requestStartTime: nil,
startTime: nil,
timestamp: "fake-time-2"
)
Expand Down Expand Up @@ -109,6 +113,10 @@ final class FPTIBatchData_Tests: XCTestCase {
XCTAssertNil(eventParams[1]["end_time"])
XCTAssertEqual(eventParams[0]["start_time"] as? Int, 999888777666)
XCTAssertNil(eventParams[1]["start_time"])
XCTAssertEqual(eventParams[0]["connect_start_time"] as? Int, 123)
XCTAssertNil(eventParams[1]["connect_start_time"])
XCTAssertEqual(eventParams[0]["request_start_time"] as? Int, 456)
XCTAssertNil(eventParams[1]["request_start_time"])
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ class FakeAnalyticsService: BTAnalyticsService {

override func sendAnalyticsEvent(
_ eventName: String,
connectionStartTime: Int? = nil,
correlationID: String? = nil,
endpoint: String? = nil,
endTime: Int? = nil,
errorDescription: String? = nil,
isVaultRequest: Bool? = nil,
linkType: String? = nil,
payPalContextID: String? = nil,
requestStartTime: Int? = nil,
startTime: Int? = nil
) {
self.lastEvent = eventName
Expand Down
24 changes: 21 additions & 3 deletions UnitTests/BraintreeCoreTests/BTAPIClient_Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,13 @@ class BTAPIClient_Tests: XCTestCase {
let mockAnalyticsService = FakeAnalyticsService(apiClient: apiClient)
apiClient.analyticsService = mockAnalyticsService

apiClient.fetchAPITiming(path: "/merchants/1234567890/client_api/v1/configuration", startTime: 12345678, endTime: 0987654)
apiClient.fetchAPITiming(
path: "/merchants/1234567890/client_api/v1/configuration",
connectionStartTime: 123,
requestStartTime: 456,
startTime: 12345678,
endTime: 0987654
)

XCTAssertEqual(mockAnalyticsService.lastEvent, "core:api-request-latency")
XCTAssertEqual(mockAnalyticsService.endpoint, "/v1/configuration")
Expand All @@ -421,7 +427,13 @@ class BTAPIClient_Tests: XCTestCase {
let mockAnalyticsService = FakeAnalyticsService(apiClient: apiClient)
apiClient.analyticsService = mockAnalyticsService

apiClient.fetchAPITiming(path: "/v1/tracking/batch/events", startTime: 12345678, endTime: 0987654)
apiClient.fetchAPITiming(
path: "/v1/tracking/batch/events",
connectionStartTime: 123,
requestStartTime: 456,
startTime: 12345678,
endTime: 0987654
)

XCTAssertNil(mockAnalyticsService.lastEvent)
XCTAssertNil(mockAnalyticsService.endpoint)
Expand All @@ -432,7 +444,13 @@ class BTAPIClient_Tests: XCTestCase {
let mockAnalyticsService = FakeAnalyticsService(apiClient: apiClient)
apiClient.analyticsService = mockAnalyticsService

apiClient.fetchAPITiming(path: "/merchants/1234567890/client_api/v1/paypal_hermes/create_payment_resource", startTime: 12345678, endTime: 0987654)
apiClient.fetchAPITiming(
path: "/merchants/1234567890/client_api/v1/paypal_hermes/create_payment_resource",
connectionStartTime: 123,
requestStartTime: 456,
startTime: 12345678,
endTime: 0987654
)

XCTAssertEqual(mockAnalyticsService.lastEvent, "core:api-request-latency")
XCTAssertEqual(mockAnalyticsService.endpoint, "/v1/paypal_hermes/create_payment_resource")
Expand Down
Loading