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

RUM-4086 Synchronize SR info with WebViews #1784

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ class WebEventIntegrationTests: XCTestCase {
"service": "super",
"session": {
"id": "0110cab4-7471-480e-aa4e-7ce039ced355",
"type": "user"
"type": "user",
"has_replay": true
},
"type": "view",
"view": {
Expand Down Expand Up @@ -90,14 +91,16 @@ class WebEventIntegrationTests: XCTestCase {
"count": 3
},
"time_spent": 3120000000,
"url": "http://localhost:8080/test.html"
"url": "http://localhost:8080/test.html",
},
"_dd": {
"document_version": 2,
"drift": 0,
"format_version": 2,
"session": {
"plan": 2
"replay_stats": {
"records_count": 10,
"segments_count": 1,
"segments_total_raw_size": 10
}
}
},
Expand Down Expand Up @@ -159,10 +162,7 @@ class WebEventIntegrationTests: XCTestCase {
"_dd": {
"document_version": 2,
"drift": 0,
"format_version": 2,
"session": {
"plan": 1
}
"format_version": 2
}
}
"""
Expand Down
25 changes: 0 additions & 25 deletions DatadogCore/Tests/Matchers/RUMSessionMatcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,11 +271,6 @@ internal class RUMSessionMatcher {
private func validate(rumViewEvents: [RUMViewEvent]) throws {
// All view events must use `session.plan` "lite"
try rumViewEvents.forEach { viewEvent in
if viewEvent.dd.session?.plan != .plan1 {
throw RUMSessionConsistencyException(
description: "All RUM events must use session plan `1` (RUM Lite). Bad view event: \(viewEvent)"
)
}
if viewEvent.source == .ios { // validete only mobile events
try validate(device: viewEvent.device)
try validate(os: viewEvent.os)
Expand All @@ -286,11 +281,6 @@ private func validate(rumViewEvents: [RUMViewEvent]) throws {
private func validate(rumActionEvents: [RUMActionEvent]) throws {
// All action events must use `session.plan` "lite"
try rumActionEvents.forEach { actionEvent in
if actionEvent.dd.session?.plan != .plan1 {
throw RUMSessionConsistencyException(
description: "All RUM events must use session plan `1` (RUM Lite). Bad action event: \(actionEvent)"
)
}
if actionEvent.source == .ios { // validete only mobile events
try validate(device: actionEvent.device)
try validate(os: actionEvent.os)
Expand All @@ -309,11 +299,6 @@ private func validate(rumResourceEvents: [RUMResourceEvent]) throws {

// All resource events must use `session.plan` "lite"
try rumResourceEvents.forEach { resourceEvent in
if resourceEvent.dd.session?.plan != .plan1 {
throw RUMSessionConsistencyException(
description: "All RUM events must use session plan `1` (RUM Lite). Bad resource event: \(resourceEvent)"
)
}
if resourceEvent.source == .ios { // validete only mobile events
try validate(device: resourceEvent.device)
try validate(os: resourceEvent.os)
Expand All @@ -324,11 +309,6 @@ private func validate(rumResourceEvents: [RUMResourceEvent]) throws {
private func validate(rumErrorEvents: [RUMErrorEvent]) throws {
// All error events must use `session.plan` "lite"
try rumErrorEvents.forEach { errorEvent in
if errorEvent.dd.session?.plan != .plan1 {
throw RUMSessionConsistencyException(
description: "All RUM events must use session plan `1` (RUM Lite). Bad error event: \(errorEvent)"
)
}
if errorEvent.source == .ios { // validete only mobile events
try validate(device: errorEvent.device)
try validate(os: errorEvent.os)
Expand All @@ -339,11 +319,6 @@ private func validate(rumErrorEvents: [RUMErrorEvent]) throws {
private func validate(rumLongTaskEvents: [RUMLongTaskEvent]) throws {
// All error events must use `session.plan` "lite"
try rumLongTaskEvents.forEach { longTaskEvent in
if longTaskEvent.dd.session?.plan != .plan1 {
throw RUMSessionConsistencyException(
description: "All RUM events must use session plan `1` (RUM Lite). Bad long task event: \(longTaskEvent)"
)
}
if longTaskEvent.source == .ios { // validete only mobile events
try validate(device: longTaskEvent.device)
try validate(os: longTaskEvent.os)
Expand Down
12 changes: 8 additions & 4 deletions DatadogRUM/Sources/Integrations/WebViewEventReceiver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,17 @@ internal final class WebViewEventReceiver: FeatureMessageReceiver {

if var session = event["session"] as? JSON {
session["id"] = rum.sessionID
// Unset `has_replay` if native replay is disabled
if context.hasReplay != true {
session["has_replay"] = context.hasReplay
}

event["session"] = session
}

if var dd = event["_dd"] as? JSON {
var session = dd["session"] as? [String: Any] ?? [:]
session["plan"] = 1
dd["session"] = session
if var dd = event["_dd"] as? JSON, context.hasReplay != true {
// Remove stats if native replay is disabled
dd["replay_stats"] = nil
event["_dd"] = dd
}

Expand Down
181 changes: 165 additions & 16 deletions DatadogRUM/Tests/Integrations/WebViewEventReceiverTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,11 @@ class WebViewEventReceiverTests: XCTestCase {

// MARK: - Modifying Web Events

func testGivenRUMContextAvailable_whenReceivingWebEvent_itGetsEnrichedWithOtherMobileContextAndWritten() throws {
func testGivenRUMContextAvailable_whenReceivingWebEvent_itInjectRUMInfo() throws {
// Given
let dateProvider = RelativeDateProvider()
let rumContext: RUMCoreContext = .mockRandom()
featureScope.contextMock = .mockWith(
source: "react-native",
baggages: [
RUMFeature.name: FeatureBaggage(rumContext)
]
Expand All @@ -245,21 +244,16 @@ class WebViewEventReceiverTests: XCTestCase {
viewCache: ViewCache(dateProvider: dateProvider)
)

let containerViewID: String = .mockRandom()
receiver.viewCache.insert(
id: containerViewID,
timestamp: dateProvider.now.timeIntervalSince1970.toInt64Milliseconds,
hasReplay: true
)

dateProvider.advance(bySeconds: 1)
let date = dateProvider.now.timeIntervalSince1970.toInt64Milliseconds
let random = mockRandomAttributes() // because below we only mock partial web event, we use this random to make the test fuzzy
let webEventMock: JSON = [
// Known properties:
"_dd": ["browser_sdk_version": "5.2.0"],
"application": ["id": String.mockRandom()],
"session": ["id": String.mockRandom()],
"session": [
"id": String.mockRandom(),
],
"view": ["id": "00000000-aaaa-0000-aaaa-000000000000"],
"date": Int(date),
].merging(random, uniquingKeysWith: { old, _ in old })
Expand All @@ -272,15 +266,12 @@ class WebViewEventReceiverTests: XCTestCase {
let expectedWebEventWritten: JSON = [
// Known properties:
"_dd": [
"session": ["plan": 1],
"browser_sdk_version": "5.2.0"
] as [String: Any],
"container": [
"source": "react-native",
"view": [ "id": containerViewID ]
] as [String: Any],
"application": ["id": rumContext.applicationID],
"session": ["id": rumContext.sessionID],
"session": [
"id": rumContext.sessionID,
],
"view": ["id": "00000000-aaaa-0000-aaaa-000000000000"],
"date": date + featureScope.contextMock.serverTimeOffset.toInt64Milliseconds,
].merging(random, uniquingKeysWith: { old, _ in old })
Expand Down Expand Up @@ -337,4 +328,162 @@ class WebViewEventReceiverTests: XCTestCase {
let errorTelemetry = try XCTUnwrap(featureScope.telemetryMock.messages.firstError(), "It must send error telemetry")
XCTAssertTrue(errorTelemetry.message.hasPrefix("Failed to decode `RUMCoreContext`"))
}

func testGivenReplayContextAvailable_whenReceivingWebEvent_itInjectReplayInfo() throws {
// Given
let dateProvider = RelativeDateProvider()
let rumContext: RUMCoreContext = .mockRandom()
featureScope.contextMock = .mockWith(
source: "react-native",
baggages: [
RUMFeature.name: FeatureBaggage(rumContext),
SessionReplayDependency.hasReplay: FeatureBaggage(true)
]
)

let receiver = WebViewEventReceiver(
featureScope: featureScope,
dateProvider: DateProviderMock(),
commandSubscriber: RUMCommandSubscriberMock(),
viewCache: ViewCache(dateProvider: dateProvider)
)

let containerViewID: String = .mockRandom()
receiver.viewCache.insert(
id: containerViewID,
timestamp: dateProvider.now.timeIntervalSince1970.toInt64Milliseconds,
hasReplay: true
)

dateProvider.advance(bySeconds: 1)
let date = dateProvider.now.timeIntervalSince1970.toInt64Milliseconds
let random = mockRandomAttributes() // because below we only mock partial web event, we use this random to make the test fuzzy
let webHasReplay: Bool = .mockRandom()
let webEventMock: JSON = [
// Known properties:
"_dd": [
"browser_sdk_version": "5.2.0",
"replay_stats": RUMViewEvent.DD.ReplayStats(
recordsCount: 10,
segmentsCount: 1,
segmentsTotalRawSize: 10
)
] as [String: Any],
"application": ["id": String.mockRandom()],
"session": [
"id": String.mockRandom(),
"has_replay": webHasReplay
] as [String: Any],
"view": ["id": "00000000-aaaa-0000-aaaa-000000000000"],
"date": Int(date),
].merging(random, uniquingKeysWith: { old, _ in old })

// When
let result = receiver.receive(message: webViewTrackingMessage(with: webEventMock), from: NOPDatadogCore())

// Then
let expectedWebEventWritten: JSON = [
// Known properties:
"_dd": [
"browser_sdk_version": "5.2.0",
"replay_stats": [
"records_count": 10,
"segments_count": 1,
"segments_total_raw_size": 10
]
] as [String: Any],
"container": [
"source": "react-native",
"view": [ "id": containerViewID ]
] as [String: Any],
"application": ["id": rumContext.applicationID],
"session": [
"id": rumContext.sessionID,
"has_replay": webHasReplay
] as [String: Any],
"view": ["id": "00000000-aaaa-0000-aaaa-000000000000"],
"date": date + featureScope.contextMock.serverTimeOffset.toInt64Milliseconds,
].merging(random, uniquingKeysWith: { old, _ in old })

XCTAssertTrue(result, "It must accept the message")
XCTAssertEqual(featureScope.eventsWritten.count, 1, "It must write web event to core")
let actualWebEventWritten = try XCTUnwrap(featureScope.eventsWritten.first)
DDAssertJSONEqual(AnyCodable(actualWebEventWritten), AnyCodable(expectedWebEventWritten))
}

func testGivenReplayContextNotAvailable_whenReceivingWebEvent_itRemovesReplayInfo() throws {
// Given
let dateProvider = RelativeDateProvider()
let rumContext: RUMCoreContext = .mockRandom()
featureScope.contextMock = .mockWith(
source: "react-native",
baggages: [
RUMFeature.name: FeatureBaggage(rumContext),
SessionReplayDependency.hasReplay: FeatureBaggage(false)
]
)

let receiver = WebViewEventReceiver(
featureScope: featureScope,
dateProvider: DateProviderMock(),
commandSubscriber: RUMCommandSubscriberMock(),
viewCache: ViewCache(dateProvider: dateProvider)
)

let containerViewID: String = .mockRandom()
receiver.viewCache.insert(
id: containerViewID,
timestamp: dateProvider.now.timeIntervalSince1970.toInt64Milliseconds,
hasReplay: true
)

dateProvider.advance(bySeconds: 1)
let date = dateProvider.now.timeIntervalSince1970.toInt64Milliseconds
let random = mockRandomAttributes() // because below we only mock partial web event, we use this random to make the test fuzzy
let webEventMock: JSON = [
// Known properties:
"_dd": [
"browser_sdk_version": "5.2.0",
"replay_stats": RUMViewEvent.DD.ReplayStats(
recordsCount: .mockRandom(),
segmentsCount: .mockRandom(),
segmentsTotalRawSize: .mockRandom()
)
] as [String: Any],
"application": ["id": String.mockRandom()],
"session": [
"id": String.mockRandom(),
"has_replay": true
] as [String: Any],
"view": ["id": "00000000-aaaa-0000-aaaa-000000000000"],
"date": Int(date),
].merging(random, uniquingKeysWith: { old, _ in old })

// When
let result = receiver.receive(message: webViewTrackingMessage(with: webEventMock), from: NOPDatadogCore())

// Then
let expectedWebEventWritten: JSON = [
// Known properties:
"_dd": [
"browser_sdk_version": "5.2.0"
] as [String: Any],
"container": [
"source": "react-native",
"view": [ "id": containerViewID ]
] as [String: Any],
"application": ["id": rumContext.applicationID],
"session": [
"id": rumContext.sessionID,
"has_replay": false
] as [String: Any],
"view": ["id": "00000000-aaaa-0000-aaaa-000000000000"],
"date": date + featureScope.contextMock.serverTimeOffset.toInt64Milliseconds,
].merging(random, uniquingKeysWith: { old, _ in old })

XCTAssertTrue(result, "It must accept the message")
XCTAssertEqual(featureScope.eventsWritten.count, 1, "It must write web event to core")
let actualWebEventWritten = try XCTUnwrap(featureScope.eventsWritten.first)
DDAssertJSONEqual(AnyCodable(actualWebEventWritten), AnyCodable(expectedWebEventWritten))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ class WebViewScenarioTest: IntegrationTests, RUMCommonAsserts {
XCTAssertEqual(browserViewEvent.session.id, expectedBrowserSessionID, "Webview events should use iOS SDK session ID")
XCTAssertEqual(browserViewEvent.service, expectedBrowserServiceName, "Webview events should use Browser SDK `service`")
XCTAssertEqual(browserViewEvent.source, .browser, "Webview events should use Browser SDK `source`")
XCTAssertEqual(browserViewEvent.dd.session?.plan, .plan1, "Webview events should use iOS SDK plan 1")
XCTAssertEqual(browserViewEvent.container?.source, .ios, "Webview events should include a container source")
XCTAssertEqual(browserViewEvent.container?.view.id, expectedBrowserContainerViewID, "Webview events should include a container view.id")
}
Expand All @@ -79,7 +78,6 @@ class WebViewScenarioTest: IntegrationTests, RUMCommonAsserts {
XCTAssertEqual(browserResourceEvent.session.id, expectedBrowserSessionID, "Webview events should use iOS SDK session ID")
XCTAssertEqual(browserResourceEvent.service, expectedBrowserServiceName, "Webview events should use Browser SDK `service`")
XCTAssertEqual(browserResourceEvent.source, .browser, "Webview events should use Browser SDK `source`")
XCTAssertEqual(browserResourceEvent.dd.session?.plan, .plan1, "Webview events should use iOS SDK plan 1")
XCTAssertEqual(browserResourceEvent.container?.source, .ios, "Webview events should use include a container view")
XCTAssertEqual(browserResourceEvent.container?.view.id, expectedBrowserContainerViewID, "Webview events should include a container view.id")
}
Expand Down