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

RUMM-1218 App going background stops active RUM view #479

Merged
merged 3 commits into from
May 5, 2021
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
10 changes: 6 additions & 4 deletions Sources/Datadog/Core/System/AppStateListener.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ internal class AppStateListener: AppStateListening {
return UIApplication.managedShared?.applicationState == .active
}

init(dateProvider: DateProvider) {
init(
dateProvider: DateProvider,
notificationCenter: NotificationCenter = .default
) {
self.dateProvider = dateProvider
let currentState = Snapshot(
isActive: AppStateListener.isAppActive,
Expand All @@ -116,9 +119,8 @@ internal class AppStateListener: AppStateListening {
)
)

let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
nc.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}

@objc
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,15 @@ internal class UIKitRUMViewsHandler: UIKitRUMViewsHandlerType {
init(
predicate: UIKitRUMViewsPredicate,
dateProvider: DateProvider,
inspector: UIKitHierarchyInspectorType = UIKitHierarchyInspector()
inspector: UIKitHierarchyInspectorType = UIKitHierarchyInspector(),
notificationCenter: NotificationCenter = .default
) {
self.predicate = predicate
self.dateProvider = dateProvider
self.inspector = inspector

notificationCenter.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}

// MARK: - UIKitRUMViewsHandlerType
Expand All @@ -52,6 +56,19 @@ internal class UIKitRUMViewsHandler: UIKitRUMViewsHandlerType {

// MARK: - Private

@objc
private func appWillResignActive() {
stop(viewController: lastStartedViewController)
}

@objc
private func appDidBecomeActive() {
if let vc = lastStartedViewController,
let rumView = predicate.rumView(for: vc) {
start(viewController: vc, rumView: rumView)
}
}

/// The `UIViewController` recently asked in `UIKitRUMViewsPredicate`.
private weak var recentlyAskedViewController: UIViewController?

Expand Down Expand Up @@ -81,16 +98,13 @@ internal class UIKitRUMViewsHandler: UIKitRUMViewsHandlerType {
)
}

if let lastStartedViewController = lastStartedViewController {
subscriber?.process(
command: RUMStopViewCommand(
time: dateProvider.currentDate(),
attributes: rumView.attributes,
identity: lastStartedViewController
)
)
}
stop(viewController: lastStartedViewController)
start(viewController: viewController, rumView: rumView)

lastStartedViewController = viewController
}

private func start(viewController: UIViewController, rumView: RUMView) {
subscriber?.process(
command: RUMStartViewCommand(
time: dateProvider.currentDate(),
Expand All @@ -100,7 +114,17 @@ internal class UIKitRUMViewsHandler: UIKitRUMViewsHandlerType {
attributes: rumView.attributes
)
)
}

lastStartedViewController = viewController
private func stop(viewController: UIViewController?) {
if let vc = viewController {
subscriber?.process(
command: RUMStopViewCommand(
time: dateProvider.currentDate(),
attributes: [:],
identity: vc
)
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ class UIKitRUMViewsHandlerTests: XCTestCase {
private let commandSubscriber = RUMCommandSubscriberMock()
private let predicate = UIKitRUMViewsPredicateMock()
private let uiKitHierarchyInspector = UIKitHierarchyInspectorMock()
private let notificationCenter = NotificationCenter()

private lazy var handler: UIKitRUMViewsHandler = {
let handler = UIKitRUMViewsHandler(
predicate: predicate,
dateProvider: dateProvider,
inspector: uiKitHierarchyInspector
inspector: uiKitHierarchyInspector,
notificationCenter: notificationCenter
)
handler.subscribe(commandsSubscriber: commandSubscriber)
return handler
Expand Down Expand Up @@ -59,8 +61,8 @@ class UIKitRUMViewsHandlerTests: XCTestCase {

// Given
predicate.resultByViewController = [
view1: .init(name: .mockRandom()),
view2: .init(name: .mockRandom()),
view1: .init(name: .mockRandom(), attributes: ["key1": "val1"]),
view2: .init(name: .mockRandom(), attributes: ["key2": "val2"]),
]

// When
Expand All @@ -74,8 +76,11 @@ class UIKitRUMViewsHandlerTests: XCTestCase {
let stopCommand = try XCTUnwrap(commandSubscriber.receivedCommands[1] as? RUMStopViewCommand)
let startCommand2 = try XCTUnwrap(commandSubscriber.receivedCommands[2] as? RUMStartViewCommand)
XCTAssertTrue(startCommand1.identity.equals(view1))
XCTAssertEqual(startCommand1.attributes as? [String: String], ["key1": "val1"])
XCTAssertTrue(stopCommand.identity.equals(view1))
XCTAssertEqual(stopCommand.attributes.count, 0)
XCTAssertTrue(startCommand2.identity.equals(view2))
XCTAssertEqual(startCommand2.attributes as? [String: String], ["key2": "val2"])
}

func testGivenAcceptingPredicate_whenViewDidAppear_itDoesNotStartTheSameRUMViewTwice() {
Expand Down Expand Up @@ -193,4 +198,49 @@ class UIKitRUMViewsHandlerTests: XCTestCase {
// Then
XCTAssertEqual(predicate.numberOfCalls, 1)
}

func testGivenRUMViewStarted_whenAppStateChanges_itStopsAndRestartsRUMView() throws {
let viewName: String = .mockRandom()
let viewControllerClassName: String = .mockRandom()
let view = createMockView(viewControllerClassName: viewControllerClassName)

// Given
predicate.result = .init(name: viewName, attributes: ["foo": "bar"])
handler.notify_viewDidAppear(viewController: view, animated: .mockAny())

// When
notificationCenter.post(name: UIApplication.willResignActiveNotification, object: nil)
dateProvider.advance(bySeconds: 1)
notificationCenter.post(name: UIApplication.didBecomeActiveNotification, object: nil)

// Then
XCTAssertEqual(commandSubscriber.receivedCommands.count, 3)

let stopCommand = try XCTUnwrap(commandSubscriber.receivedCommands[1] as? RUMStopViewCommand)
XCTAssertTrue(stopCommand.identity.equals(view))
XCTAssertEqual(stopCommand.attributes.count, 0)
XCTAssertEqual(stopCommand.time, .mockDecember15th2019At10AMUTC())

let startCommand = try XCTUnwrap(commandSubscriber.receivedCommands[2] as? RUMStartViewCommand)
XCTAssertTrue(startCommand.identity.equals(view))
XCTAssertEqual(startCommand.path, viewControllerClassName)
XCTAssertEqual(startCommand.name, viewName)
XCTAssertEqual(startCommand.attributes as? [String: String], ["foo": "bar"])
XCTAssertEqual(startCommand.time, .mockDecember15th2019At10AMUTC() + 1)
}

func testGivenRUMViewDidNotStart_whenAppStateChanges_itDoesNothing() throws {
let viewName: String = .mockRandom()

// Given
predicate.result = .init(name: viewName, attributes: ["foo": "bar"])

// When
notificationCenter.post(name: UIApplication.willResignActiveNotification, object: nil)
dateProvider.advance(bySeconds: 1)
notificationCenter.post(name: UIApplication.didBecomeActiveNotification, object: nil)

// Then
XCTAssertEqual(commandSubscriber.receivedCommands.count, 0)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,17 @@ class AppStateHistoryTests: XCTestCase {
}

class AppStateListenerTests: XCTestCase {
private let notificationCenter = NotificationCenter()

func testWhenAppResignActiveAndBecomeActive_thenAppStateHistoryIsRecorded() {
let startDate = Date.mockDecember15th2019At10AMUTC()
let listener = AppStateListener(
dateProvider: RelativeDateProvider(startingFrom: startDate, advancingBySeconds: 1.0)
dateProvider: RelativeDateProvider(startingFrom: startDate, advancingBySeconds: 1.0),
notificationCenter: notificationCenter
)

NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
notificationCenter.post(name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.post(name: UIApplication.didBecomeActiveNotification, object: nil)

let expected = AppStateHistory(
initialState: .init(isActive: true, date: startDate),
Expand All @@ -148,10 +151,11 @@ class AppStateListenerTests: XCTestCase {
func testWhenAppBecomeActiveAndResignActive_thenAppStateHistoryIsRecorded() {
let startDate = Date.mockDecember15th2019At10AMUTC()
let listener = AppStateListener(
dateProvider: RelativeDateProvider(startingFrom: startDate, advancingBySeconds: 1.0)
dateProvider: RelativeDateProvider(startingFrom: startDate, advancingBySeconds: 1.0),
notificationCenter: notificationCenter
)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.post(name: UIApplication.didBecomeActiveNotification, object: nil)
notificationCenter.post(name: UIApplication.willResignActiveNotification, object: nil)

let expected = AppStateHistory(
initialState: .init(isActive: true, date: startDate),
Expand All @@ -167,7 +171,8 @@ class AppStateListenerTests: XCTestCase {
func testWhenAppStateHistoryIsRetrieved_thenFinalDateOfHistoryChanges() {
let startDate = Date.mockDecember15th2019At10AMUTC()
let listener = AppStateListener(
dateProvider: RelativeDateProvider(startingFrom: startDate, advancingBySeconds: 1.0)
dateProvider: RelativeDateProvider(startingFrom: startDate, advancingBySeconds: 1.0),
notificationCenter: notificationCenter
)
let history1 = listener.history
let history2 = listener.history
Expand All @@ -176,12 +181,14 @@ class AppStateListenerTests: XCTestCase {
}

func testWhenAppStateListenerIsCalledFromDifferentThreads_thenItWorks() {
let listener = AppStateListener(dateProvider: SystemDateProvider())
let listener = AppStateListener(
dateProvider: SystemDateProvider(),
notificationCenter: notificationCenter
)
DispatchQueue.concurrentPerform(iterations: 10_000) { iteration in
// write
if iteration < 1_000 {
let nc = NotificationCenter.default
nc.post(
notificationCenter.post(
name: (Bool.random() ?
UIApplication.willResignActiveNotification :
UIApplication.didBecomeActiveNotification),
Expand Down