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

[WIP] RUM-8168 chore: Refine app state handling #2213

Draft
wants to merge 4 commits into
base: develop
Choose a base branch
from
Draft
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
12 changes: 12 additions & 0 deletions Datadog/Datadog.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,10 @@
6179FFDE254ADBEF00556A0B /* ObjcAppLaunchHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = 6179FFD1254ADB1100556A0B /* ObjcAppLaunchHandler.h */; settings = {ATTRIBUTES = (Public, ); }; };
617B953D24BF4D8F00E6F443 /* RUMMonitorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 617B953C24BF4D8F00E6F443 /* RUMMonitorTests.swift */; };
617B954224BF4E7600E6F443 /* RUMMonitorConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 617B954124BF4E7600E6F443 /* RUMMonitorConfigurationTests.swift */; };
618031F82D6DC430007027E3 /* Threading.swift in Sources */ = {isa = PBXBuildFile; fileRef = 618031F72D6DC430007027E3 /* Threading.swift */; };
618031F92D6DC430007027E3 /* Threading.swift in Sources */ = {isa = PBXBuildFile; fileRef = 618031F72D6DC430007027E3 /* Threading.swift */; };
618032042D6F1214007027E3 /* Assert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 618032032D6F1214007027E3 /* Assert.swift */; };
618032052D6F1214007027E3 /* Assert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 618032032D6F1214007027E3 /* Assert.swift */; };
618236892710560900125326 /* DebugWebviewViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 618236882710560900125326 /* DebugWebviewViewController.swift */; };
618353BC2A69470A0085F84A /* CoreMetricsIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 618353BB2A69470A0085F84A /* CoreMetricsIntegrationTests.swift */; };
618353BD2A69470A0085F84A /* CoreMetricsIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 618353BB2A69470A0085F84A /* CoreMetricsIntegrationTests.swift */; };
Expand Down Expand Up @@ -2530,6 +2534,8 @@
617B953F24BF4DB300E6F443 /* RUMApplicationScopeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RUMApplicationScopeTests.swift; sourceTree = "<group>"; };
617B954124BF4E7600E6F443 /* RUMMonitorConfigurationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RUMMonitorConfigurationTests.swift; sourceTree = "<group>"; };
617CD0DC24CEDDD300B0B557 /* RUMUserActionScopeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RUMUserActionScopeTests.swift; sourceTree = "<group>"; };
618031F72D6DC430007027E3 /* Threading.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Threading.swift; sourceTree = "<group>"; };
618032032D6F1214007027E3 /* Assert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Assert.swift; sourceTree = "<group>"; };
618236882710560900125326 /* DebugWebviewViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugWebviewViewController.swift; sourceTree = "<group>"; };
618353BB2A69470A0085F84A /* CoreMetricsIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreMetricsIntegrationTests.swift; sourceTree = "<group>"; };
6184751426EFCF1300C7C9C5 /* DatadogTestsObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatadogTestsObserver.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -5924,6 +5930,7 @@
isa = PBXGroup;
children = (
D23039DB298D5235001A1FA3 /* ReadWriteLock.swift */,
618031F72D6DC430007027E3 /* Threading.swift */,
D2432CF829EDB22C00D93657 /* Flushable.swift */,
);
path = Concurrency;
Expand Down Expand Up @@ -6279,6 +6286,7 @@
E2AA55E92C32C76A002FEF28 /* WatchKitExtensions.swift */,
61133BBA2423979B00786299 /* SwiftExtensions.swift */,
D29A9F9429DDB1DB005C54A4 /* UIKitExtensions.swift */,
618032032D6F1214007027E3 /* Assert.swift */,
);
path = Utils;
sourceTree = "<group>";
Expand Down Expand Up @@ -8554,6 +8562,7 @@
D2160C9A29C0DE5700FAA9A5 /* FirstPartyHosts.swift in Sources */,
D2EBEE2229BA160F00B15732 /* TracePropagationHeadersReader.swift in Sources */,
D2303A02298D5236001A1FA3 /* ReadWriteLock.swift in Sources */,
618032042D6F1214007027E3 /* Assert.swift in Sources */,
D2EBEE2429BA160F00B15732 /* W3CHTTPHeadersReader.swift in Sources */,
A7FA98CE2BA1A6930018D6B5 /* MethodCalledMetric.swift in Sources */,
D23039E8298D5236001A1FA3 /* DatadogContext.swift in Sources */,
Expand Down Expand Up @@ -8582,6 +8591,7 @@
D23039FD298D5236001A1FA3 /* DataCompression.swift in Sources */,
D2EA0F462C0E1AE300CB20F8 /* SessionReplayConfiguration.swift in Sources */,
6167E6F92B81E95900C3CA2D /* BinaryImage.swift in Sources */,
618031F82D6DC430007027E3 /* Threading.swift in Sources */,
6174D60C2BFDDEDF00EC7469 /* SDKMetricFields.swift in Sources */,
D23039F0298D5236001A1FA3 /* AnyEncoder.swift in Sources */,
D2A783D429A5309F003B03BB /* SwiftExtensions.swift in Sources */,
Expand Down Expand Up @@ -9567,6 +9577,7 @@
D2160C9B29C0DE5700FAA9A5 /* FirstPartyHosts.swift in Sources */,
D2EBEE3029BA161100B15732 /* TracePropagationHeadersReader.swift in Sources */,
D2DA2373298D57AA00C6C7E6 /* ReadWriteLock.swift in Sources */,
618032052D6F1214007027E3 /* Assert.swift in Sources */,
D2EBEE3229BA161100B15732 /* W3CHTTPHeadersReader.swift in Sources */,
A7FA98CF2BA1A6930018D6B5 /* MethodCalledMetric.swift in Sources */,
D2DA2374298D57AA00C6C7E6 /* DatadogContext.swift in Sources */,
Expand Down Expand Up @@ -9595,6 +9606,7 @@
D2DA237D298D57AA00C6C7E6 /* DataCompression.swift in Sources */,
D2C9A26A2C0F3F5A007526F5 /* SessionReplayConfiguration.swift in Sources */,
6167E6FA2B81E95900C3CA2D /* BinaryImage.swift in Sources */,
618031F92D6DC430007027E3 /* Threading.swift in Sources */,
6174D60D2BFDDEDF00EC7469 /* SDKMetricFields.swift in Sources */,
D2DA237E298D57AA00C6C7E6 /* AnyEncoder.swift in Sources */,
D2A783D529A530A0003B03BB /* SwiftExtensions.swift in Sources */,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class WebLogIntegrationTests: XCTestCase {
private var core: DatadogCoreProxy! // swiftlint:disable:this implicitly_unwrapped_optional
private var controller: WKUserContentControllerMock! // swiftlint:disable:this implicitly_unwrapped_optional

override func setUp() {
override func setUpWithError() throws {
core = DatadogCoreProxy(
context: .mockWith(
env: "test",
Expand All @@ -29,7 +29,7 @@ class WebLogIntegrationTests: XCTestCase {

controller = WKUserContentControllerMock()

WebViewTracking.enable(
try WebViewTracking.enableOrThrow(
tracking: controller,
hosts: [],
hostsSanitizer: HostsSanitizer(),
Expand Down
10 changes: 4 additions & 6 deletions Datadog/IntegrationUnitTests/RUM/StartingRUMSessionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -214,12 +214,10 @@ class StartingRUMSessionTests: XCTestCase {
launchDate: processStartTime,
isActivePrewarm: true
),
applicationStateHistory: AppStateHistory(
initialSnapshot: .init(state: .background, date: processStartTime), // active prewarm implies background
recentDate: firstRUMTime,
snapshots: [
.init(state: .active, date: firstRUMTime.addingTimeInterval(-0.5)) // become active shortly before view is started
]
applicationStateHistory: .mockWith(
initialState: .background, // active prewarm implies background
date: processStartTime,
transitions: [(state: .active, date: firstRUMTime.addingTimeInterval(-0.5))] // become active shortly before view is started
)
)
let rumTime = DateProviderMock()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class WebEventIntegrationTests: XCTestCase {
private var core: DatadogCoreProxy! // swiftlint:disable:this implicitly_unwrapped_optional
private var controller: WKUserContentControllerMock! // swiftlint:disable:this implicitly_unwrapped_optional

override func setUp() {
override func setUpWithError() throws {
core = DatadogCoreProxy(
context: .mockWith(
env: "test",
Expand All @@ -28,7 +28,7 @@ class WebEventIntegrationTests: XCTestCase {

controller = WKUserContentControllerMock()

WebViewTracking.enable(
try WebViewTracking.enableOrThrow(
tracking: controller,
hosts: [],
hostsSanitizer: HostsSanitizer(),
Expand Down
53 changes: 20 additions & 33 deletions DatadogCore/Sources/Core/Context/ApplicationStatePublisher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,6 @@ import WatchKit
#endif

internal final class ApplicationStatePublisher: ContextValuePublisher {
typealias Snapshot = AppStateHistory.Snapshot

/// The default publisher queue.
private static let defaultQueue = DispatchQueue(
label: "com.datadoghq.app-state-publisher",
target: .global(qos: .utility)
)

/// The initial history value.
let initialValue: AppStateHistory

Expand All @@ -33,18 +25,13 @@ internal final class ApplicationStatePublisher: ContextValuePublisher {
/// The date provider for the Application state snapshot timestamp.
private let dateProvider: DateProvider

/// The queue used to serialise access to the `history` and
/// to publish the new history.
private let queue: DispatchQueue

/// The current application state history.
///
/// To mutate in the `queue` only.
/// **Note**: It must be accessed from the main thread.
private var history: AppStateHistory

/// The receiver for publishing the state history.
///
/// To mutate in the `queue` only.
@ReadWriteLock
private var receiver: ContextValueReceiver<AppStateHistory>?

/// Creates a Application state publisher for publishing application state
Expand All @@ -53,30 +40,28 @@ internal final class ApplicationStatePublisher: ContextValuePublisher {
/// **Note**: It must be called on the main thread.
///
/// - Parameters:
/// - appStateProvider: The provider to access the current application state.
/// - appStateHistory: The history of app state and their transitions over time.
/// - notificationCenter: The notification center where this publisher observes `UIApplication` notifications.
/// - dateProvider: The date provider for the Application state snapshot timestamp.
/// - queue: The queue for publishing the history.
init(
appStateProvider: AppStateProvider,
appStateHistory: AppStateHistory,
notificationCenter: NotificationCenter,
dateProvider: DateProvider,
queue: DispatchQueue = ApplicationStatePublisher.defaultQueue
dateProvider: DateProvider
) {
let initialValue = AppStateHistory(
initialState: appStateProvider.current,
date: dateProvider.now
)

self.initialValue = initialValue
self.initialValue = appStateHistory
self.history = initialValue
self.queue = queue
self.dateProvider = dateProvider
self.notificationCenter = notificationCenter
}

func publish(to receiver: @escaping ContextValueReceiver<AppStateHistory>) {
queue.async { self.receiver = receiver }
// The `notificationCenter` must be subscribed to on the main thread to ensure a deterministic subscription order.
// By synchronizing on the main thread, Core will always receive app state change notifications before Features,
// even if Features implement their own subscriptions (Core is always enabled before Features).
dd_assert(Thread.isMainThread, "Must be called on the main thread")

self.receiver = receiver
notificationCenter.addObserver(self, selector: #selector(applicationDidBecomeActive), name: ApplicationNotifications.didBecomeActive, object: nil)
notificationCenter.addObserver(self, selector: #selector(applicationWillResignActive), name: ApplicationNotifications.willResignActive, object: nil)
notificationCenter.addObserver(self, selector: #selector(applicationDidEnterBackground), name: ApplicationNotifications.didEnterBackground, object: nil)
Expand Down Expand Up @@ -104,19 +89,21 @@ internal final class ApplicationStatePublisher: ContextValuePublisher {
}

private func append(state: AppState) {
let snapshot = Snapshot(state: state, date: dateProvider.now)
queue.async {
self.history.append(snapshot)
self.receiver?(self.history)
}
// This must run on the main thread for two reasons:
// - For maximum performance, `history` is lock-free and relies on synchronization through a single thread.
// - `receiver` must be updated from the main thread to ensure the new app state is always available
// for the next `eventWriteContext {}` and `context {}` request on this thread.
dd_assert(Thread.isMainThread, "Must be called on main thread")
history.append(state: state, at: dateProvider.now)
receiver?(history)
}

func cancel() {
notificationCenter.removeObserver(self, name: ApplicationNotifications.didBecomeActive, object: nil)
notificationCenter.removeObserver(self, name: ApplicationNotifications.willResignActive, object: nil)
notificationCenter.removeObserver(self, name: ApplicationNotifications.didEnterBackground, object: nil)
notificationCenter.removeObserver(self, name: ApplicationNotifications.willEnterForeground, object: nil)
queue.async { self.receiver = nil }
receiver = nil
}
}

Expand Down
29 changes: 16 additions & 13 deletions DatadogCore/Sources/Core/DatadogCore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,15 @@ extension DatadogContextProvider {
appLaunchHandler: AppLaunchHandling,
appStateProvider: AppStateProvider
) {
// `ContextProvider` must be initialized on the main thread for two key reasons:
// - It interacts with UIKit APIs to read the initial app state, which is only safe on the main thread.
// - It subscribes to app state change notifications, and we need this subscription to occur
// before any Feature subscriptions. This ensures that Core always processes state changes first.
dd_assert(Thread.isMainThread, "Must be called on main thread")

let initialAppState = appStateProvider.current
let appStateHistory = AppStateHistory(initialState: initialAppState, date: dateProvider.now)

let context = DatadogContext(
site: site,
clientToken: clientToken,
Expand All @@ -439,10 +448,7 @@ extension DatadogContextProvider {
device: device,
nativeSourceOverride: nativeSourceOverride,
launchTime: appLaunchHandler.currentValue,
// this is a placeholder waiting for the `ApplicationStatePublisher`
// to be initialized on the main thread, this value will be overrided
// as soon as the subscription is made.
applicationStateHistory: .active(since: dateProvider.now)
applicationStateHistory: appStateHistory
)

self.init(context: context)
Expand All @@ -465,15 +471,12 @@ extension DatadogContextProvider {
#endif

#if os(iOS) || os(tvOS)
DispatchQueue.main.async {
// must be call on the main thread to read `UIApplication.State`
let applicationStatePublisher = ApplicationStatePublisher(
appStateProvider: appStateProvider,
notificationCenter: notificationCenter,
dateProvider: dateProvider
)
self.subscribe(\.applicationStateHistory, to: applicationStatePublisher)
}
let applicationStatePublisher = ApplicationStatePublisher(
appStateHistory: appStateHistory,
notificationCenter: notificationCenter,
dateProvider: dateProvider
)
self.subscribe(\.applicationStateHistory, to: applicationStatePublisher)
#endif
}
}
Expand Down
15 changes: 10 additions & 5 deletions DatadogCore/Sources/Datadog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -390,11 +390,16 @@ public enum Datadog {
#endif

do {
return try initializeOrThrow(
with: configuration,
trackingConsent: trackingConsent,
instanceName: instanceName
)
// To safely instrument the application lifecycle observer and other providers,
// SDK initialization must occur on the main thread. This enforcement is also present
// in all Features, ensuring a proper registration order.
return try runOnMainThreadSync {
return try initializeOrThrow(
with: configuration,
trackingConsent: trackingConsent,
instanceName: instanceName
)
}
} catch {
consolePrint("\(error)", .error)
return NOPDatadogCore()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,6 @@ class CrashContextProviderTests: XCTestCase {
DDAssertReflectionEqual(crashContext.userInfo, sdkContext.userInfo, file: file, line: line)
XCTAssertEqual(crashContext.networkConnectionInfo, sdkContext.networkConnectionInfo, file: file, line: line)
XCTAssertEqual(crashContext.carrierInfo, sdkContext.carrierInfo, file: file, line: line)
XCTAssertEqual(crashContext.lastIsAppInForeground, sdkContext.applicationStateHistory.currentSnapshot.state.isRunningInForeground, file: file, line: line)
XCTAssertEqual(crashContext.lastIsAppInForeground, sdkContext.applicationStateHistory.currentState.isRunningInForeground, file: file, line: line)
}
}
Loading