@datadog/mobile-react-native 2.14.6 → 2.14.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/android/src/main/kotlin/com/datadog/reactnative/DdSdkImplementation.kt +13 -5
  2. package/android/src/main/kotlin/com/datadog/reactnative/DdSdkNativeInitialization.kt +13 -6
  3. package/android/src/main/kotlin/com/datadog/reactnative/DdSdkSessionStartedListener.kt +93 -22
  4. package/android/src/main/kotlin/com/datadog/reactnative/FrameRateProvider.kt +16 -8
  5. package/android/src/main/kotlin/com/datadog/reactnative/JsThreadExecutor.kt +27 -0
  6. package/android/src/main/kotlin/com/datadog/reactnative/SdkVersion.kt +1 -1
  7. package/android/src/test/kotlin/com/datadog/reactnative/DdSdkNativeInitializationTest.kt +68 -0
  8. package/android/src/test/kotlin/com/datadog/reactnative/DdSdkSessionStartedListenerTest.kt +38 -1
  9. package/android/src/test/kotlin/com/datadog/reactnative/DdSdkTest.kt +7 -5
  10. package/android/src/test/kotlin/com/datadog/tools/unit/TestJsThreadExecutor.kt +16 -0
  11. package/ios/Sources/DdSdkNativeInitialization.swift +24 -18
  12. package/ios/Sources/DdSdkSessionStartedListener.swift +28 -1
  13. package/ios/Sources/SdkVersion.swift +1 -1
  14. package/lib/commonjs/DdSdkReactNative.js +10 -1
  15. package/lib/commonjs/DdSdkReactNative.js.map +1 -1
  16. package/lib/commonjs/DdSdkReactNativeConfiguration.js.map +1 -1
  17. package/lib/commonjs/metro/debugIdResolver.js +5 -3
  18. package/lib/commonjs/metro/debugIdResolver.js.map +1 -1
  19. package/lib/commonjs/metro/plugin/metroSerializer.js +4 -3
  20. package/lib/commonjs/metro/plugin/metroSerializer.js.map +1 -1
  21. package/lib/commonjs/rum/instrumentation/resourceTracking/DdRumResourceTracking.js +20 -0
  22. package/lib/commonjs/rum/instrumentation/resourceTracking/DdRumResourceTracking.js.map +1 -1
  23. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js +12 -4
  24. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js.map +1 -1
  25. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/interfaces/RequestProxy.js.map +1 -1
  26. package/lib/commonjs/version.js +1 -1
  27. package/lib/module/DdSdkReactNative.js +10 -1
  28. package/lib/module/DdSdkReactNative.js.map +1 -1
  29. package/lib/module/DdSdkReactNativeConfiguration.js.map +1 -1
  30. package/lib/module/metro/debugIdResolver.js +5 -3
  31. package/lib/module/metro/debugIdResolver.js.map +1 -1
  32. package/lib/module/metro/plugin/metroSerializer.js +4 -3
  33. package/lib/module/metro/plugin/metroSerializer.js.map +1 -1
  34. package/lib/module/rum/instrumentation/resourceTracking/DdRumResourceTracking.js +20 -0
  35. package/lib/module/rum/instrumentation/resourceTracking/DdRumResourceTracking.js.map +1 -1
  36. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js +12 -4
  37. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js.map +1 -1
  38. package/lib/module/version.js +1 -1
  39. package/lib/typescript/DdSdkReactNative.d.ts.map +1 -1
  40. package/lib/typescript/DdSdkReactNativeConfiguration.d.ts +1 -0
  41. package/lib/typescript/DdSdkReactNativeConfiguration.d.ts.map +1 -1
  42. package/lib/typescript/metro/debugIdResolver.d.ts.map +1 -1
  43. package/lib/typescript/metro/plugin/metroSerializer.d.ts +1 -1
  44. package/lib/typescript/metro/plugin/metroSerializer.d.ts.map +1 -1
  45. package/lib/typescript/rum/instrumentation/resourceTracking/DdRumResourceTracking.d.ts +11 -0
  46. package/lib/typescript/rum/instrumentation/resourceTracking/DdRumResourceTracking.d.ts.map +1 -1
  47. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.d.ts +2 -0
  48. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.d.ts.map +1 -1
  49. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/interfaces/RequestProxy.d.ts +1 -0
  50. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/interfaces/RequestProxy.d.ts.map +1 -1
  51. package/lib/typescript/version.d.ts +1 -1
  52. package/package.json +2 -2
  53. package/src/DdSdkReactNative.tsx +17 -6
  54. package/src/DdSdkReactNativeConfiguration.tsx +1 -0
  55. package/src/metro/__tests__/metro.test.ts +13 -0
  56. package/src/metro/debugIdResolver.ts +7 -3
  57. package/src/metro/plugin/metroSerializer.ts +11 -3
  58. package/src/rum/instrumentation/resourceTracking/DdRumResourceTracking.tsx +25 -0
  59. package/src/rum/instrumentation/resourceTracking/__tests__/DdRumResourceTracking.test.ts +111 -0
  60. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.ts +13 -4
  61. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/__tests__/XHRProxy.test.ts +68 -0
  62. package/src/rum/instrumentation/resourceTracking/requestProxy/interfaces/RequestProxy.ts +1 -0
  63. package/src/version.ts +1 -1
@@ -24,7 +24,8 @@ import java.util.concurrent.atomic.AtomicBoolean
24
24
  class DdSdkImplementation(
25
25
  private val reactContext: ReactApplicationContext,
26
26
  private val datadog: DatadogWrapper = DatadogSDKWrapper(),
27
- private val uiThreadExecutor: UiThreadExecutor = ReactUiThreadExecutor()
27
+ private val uiThreadExecutor: UiThreadExecutor = ReactUiThreadExecutor(),
28
+ private val jsThreadExecutor: JsThreadExecutor = ReactJsThreadExecutor(reactContext)
28
29
  ) {
29
30
  internal val appContext: Context = reactContext.applicationContext
30
31
  internal val initialized = AtomicBoolean(false)
@@ -39,6 +40,15 @@ class DdSdkImplementation(
39
40
  fun initialize(configuration: ReadableMap, promise: Promise) {
40
41
  val ddSdkConfiguration = configuration.asDdSdkConfiguration()
41
42
 
43
+ // On new arch DdSdk is a lazy TurboModule — it's instantiated on the first JS-side
44
+ // method call (typically this initialize()), which usually lands AFTER the activity's
45
+ // first onHostResume. That means registerLifecycleEvents's listener missed the first
46
+ // resume, reactContext is still null on the session listener, and the replay inside
47
+ // nativeInitialization.initialize → onRnSdkInitialized has no emitter target. Setting
48
+ // the reactContext here — we are provably being dispatched through an active one —
49
+ // closes that race so the cached session ID is delivered on the first JS init.
50
+ DdSdkSessionStartedListener.getInstance().setReactContext(reactContext)
51
+
42
52
  val nativeInitialization = DdSdkNativeInitialization(appContext, datadog)
43
53
  nativeInitialization.initialize(ddSdkConfiguration)
44
54
 
@@ -232,10 +242,8 @@ class DdSdkImplementation(
232
242
  ddSdkConfiguration: DdSdkConfiguration
233
243
  ): FrameRateProvider? {
234
244
  val frameTimeCallback = buildFrameTimeCallback(ddSdkConfiguration) ?: return null
235
- val frameRateProvider = FrameRateProvider(frameTimeCallback, uiThreadExecutor)
236
- reactContext.runOnJSQueueThread {
237
- frameRateProvider.start()
238
- }
245
+ val frameRateProvider = FrameRateProvider(frameTimeCallback, jsThreadExecutor)
246
+ frameRateProvider.start()
239
247
 
240
248
  return frameRateProvider
241
249
  }
@@ -39,7 +39,7 @@ class DdSdkNativeInitialization internal constructor(
39
39
  private val datadog: DatadogWrapper = DatadogSDKWrapper(),
40
40
  private val jsonFileReader: JSONFileReader = JSONFileReader()
41
41
  ) {
42
- internal fun initialize(ddSdkConfiguration: DdSdkConfiguration) {
42
+ internal fun initialize(ddSdkConfiguration: DdSdkConfiguration, isCalledFromJs: Boolean = true) {
43
43
  val sdkConfiguration = buildSdkConfiguration(ddSdkConfiguration)
44
44
  val rumConfiguration = buildRumConfiguration(ddSdkConfiguration)
45
45
  val logsConfiguration = buildLogsConfiguration(ddSdkConfiguration)
@@ -49,10 +49,14 @@ class DdSdkNativeInitialization internal constructor(
49
49
  configureSdkVerbosity(ddSdkConfiguration)
50
50
  configureRumAndTracesForLogs(ddSdkConfiguration)
51
51
 
52
- if (datadog.isInitialized()) {
53
- datadog.getRumMonitor().getCurrentSessionId {
54
- it?.let { sessionId ->
55
- DdSdkSessionStartedListener.getInstance().onSessionStarted(sessionId, false)
52
+ if (isCalledFromJs) {
53
+ DdSdkSessionStartedListener.getInstance().onRnSdkInitialized()
54
+ // Handles the case in which the SDK was already initialized with initFromNative.
55
+ if (datadog.isInitialized()) {
56
+ datadog.getRumMonitor().getCurrentSessionId {
57
+ it?.let { sessionId ->
58
+ DdSdkSessionStartedListener.getInstance().onSessionStarted(sessionId, false)
59
+ }
56
60
  }
57
61
  }
58
62
  }
@@ -376,7 +380,10 @@ class DdSdkNativeInitialization internal constructor(
376
380
  fun initFromNative(appContext: Context) {
377
381
  val nativeInitialization = DdSdkNativeInitialization(appContext.applicationContext)
378
382
  try {
379
- nativeInitialization.initialize(nativeInitialization.getConfigurationFromJSONFile())
383
+ nativeInitialization.initialize(
384
+ ddSdkConfiguration = nativeInitialization.getConfigurationFromJSONFile(),
385
+ isCalledFromJs = false
386
+ )
380
387
  } catch (@Suppress("TooGenericExceptionCaught") error: Exception) {
381
388
  Log.w(
382
389
  DdSdkNativeInitialization::class.java.canonicalName,
@@ -14,13 +14,27 @@ import com.facebook.react.modules.core.DeviceEventManagerModule
14
14
  import org.jetbrains.annotations.TestOnly
15
15
 
16
16
 
17
- internal class DdSdkSessionStartedListener private constructor(): RumSessionListener {
17
+ internal class DdSdkSessionStartedListener private constructor() : RumSessionListener {
18
18
  companion object {
19
+ // JS-side callable module registered via BatchedBridge.registerCallableModule.
19
20
  private const val BRIDGE_MODULE_NAME = "DatadogInternalReactBridge"
20
21
  private const val BRIDGE_MODULE_METHOD = "__datadogOnMessageReceived"
21
22
 
22
23
  private var instance: DdSdkSessionStartedListener? = null
23
24
 
25
+ // Process-level state — tracks whether JS initialize() has ever run since the
26
+ // app process started. Kept outside the instance on purpose: the listener
27
+ // singleton is recreated on every onHostPause/onHostDestroy via invalidate(),
28
+ // but the JS bridge module registration survives activity lifecycle events, so
29
+ // this flag must survive them too.
30
+ private var isRnSdkInitialized: Boolean = false
31
+
32
+ // Routes UI-thread dispatch through an injectable abstraction. Tests inject
33
+ // TestUiThreadExecutor (synchronous, no main looper required) instead of the
34
+ // real ReactUiThreadExecutor that wraps UiThreadUtil.
35
+ private var uiThreadExecutor: UiThreadExecutor = ReactUiThreadExecutor()
36
+
37
+ // Returns the shared listener instance, creating it on first call.
24
38
  fun getInstance(): DdSdkSessionStartedListener {
25
39
  if (instance == null) {
26
40
  instance = DdSdkSessionStartedListener()
@@ -28,26 +42,67 @@ internal class DdSdkSessionStartedListener private constructor(): RumSessionList
28
42
  return instance!!
29
43
  }
30
44
 
45
+ // Resets the singleton — used in tests and on host pause/destroy to release the
46
+ // React context reference. Does NOT reset isRnSdkInitialized, which tracks
47
+ // process-level JS-bridge registration state.
31
48
  fun invalidate() {
32
49
  instance = null
33
50
  }
51
+
52
+ @TestOnly
53
+ fun resetIsRnSdkInitialized() {
54
+ isRnSdkInitialized = false
55
+ }
56
+
57
+ @TestOnly
58
+ fun isRnSdkInitializedForTests(): Boolean = isRnSdkInitialized
34
59
  }
35
60
 
36
- private var reactContext: ReactContext? = null
61
+ // Cached so it can be delivered once the bridge becomes available.
37
62
  private var lastSessionId: String? = null
63
+
64
+ // Set from onHostResume; null until the React activity is first resumed.
65
+ private var reactContext: ReactContext? = null
66
+ // Overridable in tests — NativeArray cannot be instantiated without the native SO.
38
67
  private var convertToNativeArray: ((array: Array<String>) -> NativeArray?)? = null
39
- private var exceptionHandler: ((error:Exception)->Unit)? = null
68
+ // Overridable in tests to assert on bridge exceptions without crashing.
69
+ private var exceptionHandler: ((error: Exception) -> Unit)? = null
70
+ // Lazily resolved from BuildConfig; overridable in tests.
40
71
  private var isNewArchitecture: Boolean? = null
41
72
 
73
+ // Stores the session ID and attempts immediate delivery.
42
74
  override fun onSessionStarted(sessionId: String, isDiscarded: Boolean) {
43
- sendSessionStartedToJS(sessionId)
75
+ this.lastSessionId = sessionId
76
+ trySendSessionStartedToJS(sessionId)
44
77
  }
45
78
 
79
+ // Stores the React context and schedules a catch-up delivery for any cached session
80
+ // ID on the UI thread. Called from:
81
+ // - DdSdk#onHostResume (both architectures) via the lifecycle listener
82
+ // - DdSdkImplementation#initialize (new-arch race fix — the TurboModule is lazy-
83
+ // instantiated, so the first onHostResume may have fired before its lifecycle
84
+ // listener was registered; setting the context here guarantees a non-null
85
+ // target for onRnSdkInitialized's replay)
86
+ //
87
+ // Delivery is dispatched to the UI thread because sendSessionIdWithBridge and
88
+ // sendSessionIdWithEventEmitter are @MainThread. The field assignment stays
89
+ // synchronous so callers that rely on reactContext being set immediately after
90
+ // this call (e.g. a same-stack onRnSdkInitialized) see the new value.
46
91
  fun setReactContext(reactContext: ReactContext) {
47
92
  this.reactContext = reactContext
48
- if (hasValidBridge()) {
49
- this.lastSessionId?.let { sendSessionStartedToJS(it) }
50
- }
93
+ val cached = this.lastSessionId ?: return
94
+ uiThreadExecutor.runOnUiThread { trySendSessionStartedToJS(cached) }
95
+ }
96
+
97
+ // Called when the RN SDK is initialized from JS for the first time while the native
98
+ // SDK was already running. At this point DatadogInternalReactBridge is guaranteed to
99
+ // be registered, so it is safe to deliver any session ID that was stored before the
100
+ // React bridge was available. Delivery is posted to the UI thread for the same
101
+ // reason as setReactContext.
102
+ fun onRnSdkInitialized() {
103
+ isRnSdkInitialized = true
104
+ val cached = this.lastSessionId ?: return
105
+ uiThreadExecutor.runOnUiThread { trySendSessionStartedToJS(cached) }
51
106
  }
52
107
 
53
108
  @TestOnly
@@ -65,14 +120,28 @@ internal class DdSdkSessionStartedListener private constructor(): RumSessionList
65
120
  this.isNewArchitecture = isNewArch
66
121
  }
67
122
 
123
+ @TestOnly
124
+ fun setIsRnSdkInitialized(value: Boolean) {
125
+ isRnSdkInitialized = value
126
+ }
127
+
128
+ @TestOnly
129
+ fun setUiThreadExecutor(executor: UiThreadExecutor) {
130
+ uiThreadExecutor = executor
131
+ }
132
+
133
+ // Returns true only when it is safe to call callFunction on the JS thread.
68
134
  private fun hasValidBridge(): Boolean {
69
135
  val context = reactContext ?: return false
70
136
  val instance = context.catalystInstance ?: return false
71
137
  return !isNewArchitecture() &&
72
138
  !instance.isDestroyed &&
73
- context.hasActiveReactInstance()
139
+ context.hasActiveReactInstance() &&
140
+ isRnSdkInitialized
74
141
  }
75
142
 
143
+ // Lazily cached — BuildConfig is a compile-time constant but reading it through the
144
+ // nullable override lets tests inject the value without reflection.
76
145
  private fun isNewArchitecture(): Boolean {
77
146
  isNewArchitecture?.let { return it }
78
147
  BuildConfig.IS_NEW_ARCHITECTURE_ENABLED.let {
@@ -81,8 +150,8 @@ internal class DdSdkSessionStartedListener private constructor(): RumSessionList
81
150
  }
82
151
  }
83
152
 
84
- private fun sendSessionStartedToJS(sessionId: String) {
85
- this.lastSessionId = sessionId
153
+ // Routes delivery to the appropriate path based on arch and bridge readiness.
154
+ private fun trySendSessionStartedToJS(sessionId: String) {
86
155
  if (hasValidBridge()) {
87
156
  sendSessionIdWithBridge(sessionId)
88
157
  } else {
@@ -90,30 +159,32 @@ internal class DdSdkSessionStartedListener private constructor(): RumSessionList
90
159
  }
91
160
  }
92
161
 
162
+ // Old-arch delivery path via BatchedBridge.
93
163
  @MainThread
94
164
  private fun sendSessionIdWithBridge(sessionId: String) {
95
165
  @Suppress("TooGenericExceptionCaught")
96
166
  try {
97
- val args = arrayOf(sessionId)
98
- val nativeArray = if (convertToNativeArray != null) {
99
- convertToNativeArray?.invoke(args)
100
- } else {
101
- WritableNativeArray().apply {
102
- pushString("RUMSessionStarted")
103
- pushString(sessionId)
104
- }
105
- }
106
-
167
+ val args = arrayOf("RUMSessionStarted", sessionId)
107
168
  reactContext?.catalystInstance?.callFunction(
108
169
  BRIDGE_MODULE_NAME,
109
170
  BRIDGE_MODULE_METHOD,
110
- nativeArray
171
+ buildBridgeArgs(args)
111
172
  )
112
- } catch(err: Exception) {
173
+ } catch (err: Exception) {
113
174
  exceptionHandler?.invoke(err)
114
175
  }
115
176
  }
116
177
 
178
+ private fun buildBridgeArgs(args: Array<String>): NativeArray? {
179
+ if (convertToNativeArray != null) {
180
+ return convertToNativeArray?.invoke(args)
181
+ }
182
+ return WritableNativeArray().apply {
183
+ args.forEach { pushString(it) }
184
+ }
185
+ }
186
+
187
+ // New-arch delivery path and fallback when the bridge is not active.
117
188
  @MainThread
118
189
  private fun sendSessionIdWithEventEmitter(sessionId: String) {
119
190
  val context = reactContext ?: return
@@ -10,11 +10,11 @@ import android.view.Choreographer
10
10
 
11
11
  internal class FrameRateProvider(
12
12
  reactFrameRateCallback: ((Double) -> Unit),
13
- uiThreadExecutor: UiThreadExecutor
13
+ jsThreadExecutor: JsThreadExecutor
14
14
  ) {
15
15
  private val frameCallback: FpsFrameCallback = FpsFrameCallback(
16
16
  reactFrameRateCallback,
17
- uiThreadExecutor
17
+ jsThreadExecutor
18
18
  )
19
19
 
20
20
  fun start() {
@@ -29,7 +29,7 @@ internal class FrameRateProvider(
29
29
 
30
30
  internal class FpsFrameCallback(
31
31
  private val reactFrameRateCallback: ((Double) -> Unit),
32
- private val uiThreadExecutor: UiThreadExecutor
32
+ private val jsThreadExecutor: JsThreadExecutor
33
33
  ) : Choreographer.FrameCallback {
34
34
 
35
35
  private var choreographer: Choreographer? = null
@@ -43,16 +43,24 @@ internal class FpsFrameCallback(
43
43
  choreographer?.postFrameCallback(this)
44
44
  }
45
45
 
46
+ @Suppress("SwallowedException")
46
47
  fun start() {
47
- uiThreadExecutor.runOnUiThread {
48
- choreographer = Choreographer.getInstance()
49
- choreographer?.postFrameCallback(this@FpsFrameCallback)
48
+ // Choreographer is thread-local: we register on the JS thread so frame callbacks
49
+ // measure JS frame timings, matching the iOS CADisplayLink-on-JS-RunLoop approach.
50
+ jsThreadExecutor.runOnJsThread {
51
+ try {
52
+ val instance = Choreographer.getInstance()
53
+ instance.removeFrameCallback(this@FpsFrameCallback)
54
+ choreographer = instance
55
+ instance.postFrameCallback(this@FpsFrameCallback)
56
+ } catch (e: IllegalStateException) {
57
+ // Choreographer requires a Looper; guard defensively in case the JS thread lacks one.
58
+ }
50
59
  }
51
60
  }
52
61
 
53
62
  fun stop() {
54
- uiThreadExecutor.runOnUiThread {
55
- choreographer = Choreographer.getInstance()
63
+ jsThreadExecutor.runOnJsThread {
56
64
  choreographer?.removeFrameCallback(this@FpsFrameCallback)
57
65
  }
58
66
  }
@@ -0,0 +1,27 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ package com.datadog.reactnative
8
+
9
+ import com.facebook.react.bridge.ReactApplicationContext
10
+
11
+ /**
12
+ * Simple JS Thread Executor. By default it is based on [ReactApplicationContext.runOnJSQueueThread].
13
+ */
14
+ interface JsThreadExecutor {
15
+ /**
16
+ * Runs the given runnable on the JS Thread.
17
+ */
18
+ fun runOnJsThread(runnable: Runnable)
19
+ }
20
+
21
+ internal class ReactJsThreadExecutor(
22
+ private val reactContext: ReactApplicationContext
23
+ ) : JsThreadExecutor {
24
+ override fun runOnJsThread(runnable: Runnable) {
25
+ reactContext.runOnJSQueueThread(runnable)
26
+ }
27
+ }
@@ -7,4 +7,4 @@
7
7
  package com.datadog.reactnative
8
8
 
9
9
  // This is automatically updated by the update-version.sh script
10
- internal const val SDK_VERSION = "2.14.6"
10
+ internal const val SDK_VERSION = "2.14.8"
@@ -7,6 +7,7 @@
7
7
  package com.datadog.reactnative
8
8
 
9
9
  import android.content.pm.PackageInfo
10
+ import com.datadog.android.rum.RumMonitor
10
11
  import com.datadog.tools.unit.GenericAssert.Companion.assertThat
11
12
  import com.datadog.tools.unit.forge.BaseConfigurator
12
13
  import com.facebook.react.bridge.ReactApplicationContext
@@ -24,8 +25,12 @@ import org.mockito.Answers
24
25
  import org.mockito.Mock
25
26
  import org.mockito.junit.jupiter.MockitoExtension
26
27
  import org.mockito.junit.jupiter.MockitoSettings
28
+ import org.mockito.kotlin.any
27
29
  import org.mockito.kotlin.doReturn
28
30
  import org.mockito.kotlin.isNull
31
+ import org.mockito.kotlin.mock
32
+ import org.mockito.kotlin.never
33
+ import org.mockito.kotlin.verify
29
34
  import org.mockito.kotlin.whenever
30
35
  import org.mockito.quality.Strictness
31
36
 
@@ -66,6 +71,9 @@ internal class DdSdkNativeInitializationTest {
66
71
  mockDatadog,
67
72
  mockJSONFileReader
68
73
  )
74
+
75
+ DdSdkSessionStartedListener.invalidate()
76
+ DdSdkSessionStartedListener.resetIsRnSdkInitialized()
69
77
  }
70
78
 
71
79
  // region getConfigurationFromJSONFile
@@ -180,4 +188,64 @@ internal class DdSdkNativeInitializationTest {
180
188
  }
181
189
 
182
190
  // endregion
191
+
192
+ // region initialize()
193
+
194
+ @Test
195
+ fun `𝕄 mark RN SDK initialized and catch up session 𝕎 initialize() { isCalledFromJs=true, datadog already initialized }`() { // ktlint-disable-line max-line-length
196
+ // Given
197
+ val mockRumMonitor: RumMonitor = mock()
198
+ whenever(mockDatadog.isInitialized()) doReturn true
199
+ whenever(mockDatadog.getRumMonitor()) doReturn mockRumMonitor
200
+
201
+ // When
202
+ testedNativeInitialization.initialize(
203
+ ddSdkConfiguration = minimalConfiguration(),
204
+ isCalledFromJs = true
205
+ )
206
+
207
+ // Then
208
+ assertThat(DdSdkSessionStartedListener.isRnSdkInitializedForTests()).isTrue()
209
+ verify(mockRumMonitor).getCurrentSessionId(any())
210
+ }
211
+
212
+ @Test
213
+ fun `𝕄 mark RN SDK initialized without catch up 𝕎 initialize() { isCalledFromJs=true, datadog not initialized }`() { // ktlint-disable-line max-line-length
214
+ // Given
215
+ whenever(mockDatadog.isInitialized()) doReturn false
216
+
217
+ // When
218
+ testedNativeInitialization.initialize(
219
+ ddSdkConfiguration = minimalConfiguration(),
220
+ isCalledFromJs = true
221
+ )
222
+
223
+ // Then
224
+ assertThat(DdSdkSessionStartedListener.isRnSdkInitializedForTests()).isTrue()
225
+ verify(mockDatadog, never()).getRumMonitor()
226
+ }
227
+
228
+ @Test
229
+ fun `𝕄 not mark RN SDK initialized or catch up 𝕎 initialize() { isCalledFromJs=false }`() {
230
+ // Given
231
+ whenever(mockDatadog.isInitialized()) doReturn true
232
+
233
+ // When
234
+ testedNativeInitialization.initialize(
235
+ ddSdkConfiguration = minimalConfiguration(),
236
+ isCalledFromJs = false
237
+ )
238
+
239
+ // Then
240
+ assertThat(DdSdkSessionStartedListener.isRnSdkInitializedForTests()).isFalse()
241
+ verify(mockDatadog, never()).getRumMonitor()
242
+ }
243
+
244
+ // endregion
245
+
246
+ private fun minimalConfiguration(): DdSdkConfiguration = DdSdkConfiguration(
247
+ clientToken = "fake-client-token",
248
+ env = "fake-env",
249
+ applicationId = "fake-app-id"
250
+ )
183
251
  }
@@ -8,6 +8,7 @@
8
8
  package com.datadog.reactnative
9
9
 
10
10
  import com.datadog.tools.unit.GenericAssert.Companion.assertThat
11
+ import com.datadog.tools.unit.TestUiThreadExecutor
11
12
  import com.datadog.tools.unit.forge.BaseConfigurator
12
13
  import com.facebook.react.bridge.CatalystInstance
13
14
  import com.facebook.react.bridge.NativeArray
@@ -55,6 +56,8 @@ internal class DdSdkSessionStartedListenerTest {
55
56
  @BeforeEach
56
57
  fun `set up`() {
57
58
  DdSdkSessionStartedListener.invalidate()
59
+ DdSdkSessionStartedListener.resetIsRnSdkInitialized()
60
+ DdSdkSessionStartedListener.getInstance().setUiThreadExecutor(TestUiThreadExecutor())
58
61
  }
59
62
 
60
63
  @Test
@@ -91,6 +94,7 @@ internal class DdSdkSessionStartedListenerTest {
91
94
  instance.setReactContext(mockReactContext)
92
95
  instance.setExceptionHandler(mockExceptionHandler)
93
96
  instance.setIsNewArchitecture(false)
97
+ instance.setIsRnSdkInitialized(true)
94
98
 
95
99
  val passedArgs = mutableListOf<String>()
96
100
  instance.setConvertToNativeArray {
@@ -111,6 +115,36 @@ internal class DdSdkSessionStartedListenerTest {
111
115
  )
112
116
  }
113
117
 
118
+ @Test
119
+ fun `𝕄 session ID is NOT sent via bridge W { setReactContext fires before onRnSdkInitialized }`() { // ktlint-disable-line max-line-length
120
+ // GIVEN — bridge looks valid but RN SDK has not called initialize() from JS yet
121
+ whenever(mockReactContext.hasActiveReactInstance()).thenReturn(true)
122
+ whenever(mockReactContext.catalystInstance).thenReturn(mockCatalystInstance)
123
+ whenever(mockCatalystInstance.isDestroyed).thenReturn(false)
124
+ whenever(mockReactContext.fabricUIManager).thenReturn(null)
125
+
126
+ val instance = DdSdkSessionStartedListener.getInstance()
127
+
128
+ val mockConvertToNativeArray = mock<(array: Array<String>) -> NativeArray?>()
129
+ instance.setConvertToNativeArray(mockConvertToNativeArray)
130
+ instance.setIsNewArchitecture(false)
131
+
132
+ // WHEN — native session starts and context becomes available before JS initialize()
133
+ instance.onSessionStarted("TEST-SESSION-ID", false)
134
+ instance.setReactContext(mockReactContext)
135
+
136
+ // THEN — bridge must NOT be called (DatadogInternalReactBridge not yet registered)
137
+ verifyNoInteractions(mockConvertToNativeArray)
138
+
139
+ // WHEN — JS initialize() runs, guaranteeing the callable module is registered
140
+ instance.onRnSdkInitialized()
141
+
142
+ // THEN — catch-up delivery is now safe and matches __datadogOnMessageReceived(eventName, data)
143
+ verify(mockConvertToNativeArray).invoke(
144
+ argWhere { it.size == 2 && it[0] == "RUMSessionStarted" && it[1] == "TEST-SESSION-ID" }
145
+ )
146
+ }
147
+
114
148
  @Test
115
149
  fun `𝕄 session ID event is delayed until context is available W { bridge }`() {
116
150
  // GIVEN
@@ -134,9 +168,12 @@ internal class DdSdkSessionStartedListenerTest {
134
168
  verifyNoInteractions(mockConvertToNativeArray)
135
169
 
136
170
  // WHEN
171
+ instance.setIsRnSdkInitialized(true)
137
172
  instance.setReactContext(mockReactContext)
138
173
 
139
174
  // THEN
140
- verify(mockConvertToNativeArray).invoke(argWhere { it.first() == "TEST-SESSION-ID" })
175
+ verify(mockConvertToNativeArray).invoke(
176
+ argWhere { it.size == 2 && it[0] == "RUMSessionStarted" && it[1] == "TEST-SESSION-ID" }
177
+ )
141
178
  }
142
179
  }
@@ -31,6 +31,7 @@ import com.datadog.android.trace.TraceConfiguration
31
31
  import com.datadog.android.trace.TracingHeaderType
32
32
  import com.datadog.tools.unit.GenericAssert.Companion.assertThat
33
33
  import com.datadog.tools.unit.MockRumMonitor
34
+ import com.datadog.tools.unit.TestJsThreadExecutor
34
35
  import com.datadog.tools.unit.TestUiThreadExecutor
35
36
  import com.datadog.tools.unit.forge.BaseConfigurator
36
37
  import com.datadog.tools.unit.setStaticValue
@@ -153,11 +154,12 @@ internal class DdSdkTest {
153
154
  0
154
155
  )
155
156
  ) doReturn mockPackageInfo
156
- whenever(mockReactContext.runOnJSQueueThread(any())).thenAnswer { answer ->
157
- answer.getArgument<Runnable>(0).run()
158
- true
159
- }
160
- testedBridgeSdk = DdSdkImplementation(mockReactContext, mockDatadog, TestUiThreadExecutor())
157
+ testedBridgeSdk = DdSdkImplementation(
158
+ mockReactContext,
159
+ mockDatadog,
160
+ TestUiThreadExecutor(),
161
+ TestJsThreadExecutor()
162
+ )
161
163
 
162
164
  DatadogSDKWrapperStorage.setSdkCore(null)
163
165
  DatadogSDKWrapperStorage.onInitializedListeners.clear()
@@ -0,0 +1,16 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ package com.datadog.tools.unit
8
+
9
+ import com.datadog.reactnative.JsThreadExecutor
10
+
11
+ internal class TestJsThreadExecutor : JsThreadExecutor {
12
+ override fun runOnJsThread(runnable: Runnable) {
13
+ // Run immediately in the same thread for tests
14
+ runnable.run()
15
+ }
16
+ }
@@ -32,33 +32,39 @@ public class DdSdkNativeInitialization: NSObject {
32
32
  self.jsonFileReader = jsonFileReader
33
33
  }
34
34
 
35
- internal func initialize(sdkConfiguration: DdSdkConfiguration) {
36
- // TODO: see if this `if` is still needed
35
+ internal func initialize(sdkConfiguration: DdSdkConfiguration, isCalledFromJs: Bool = true) {
37
36
  if DatadogSDKWrapper.shared.isInitialized() {
38
37
  // Initializing the SDK twice results in Global.rum and
39
38
  // Global.sharedTracer to be set to no-op instances
40
39
  consolePrint("Datadog SDK is already initialized, skipping initialization.", .debug)
41
40
  DatadogSDKWrapper.shared.telemetryDebug(id: "datadog_react_native: RN SDK was already initialized in native", message: "RN SDK was already initialized in native")
41
+ } else {
42
+ self.setVerbosityLevel(configuration: sdkConfiguration)
42
43
 
43
- RUMMonitor.shared().currentSessionID { sessionId in
44
- guard let id = sessionId else { return }
45
- DdSdkSessionStartedListener.instance.rumSessionListener?(id, false)
46
- }
44
+ let coreConfiguration = self.buildSDKConfiguration(configuration: sdkConfiguration)
45
+ DatadogSDKWrapper.shared.initialize(
46
+ coreConfiguration: coreConfiguration,
47
+ loggerConfiguration: DatadogLogs.Logger.Configuration(sdkConfiguration),
48
+ trackingConsent: sdkConfiguration.trackingConsent
49
+ )
47
50
 
48
- return
51
+ self.enableFeatures(sdkConfiguration: sdkConfiguration)
49
52
  }
50
- self.setVerbosityLevel(configuration: sdkConfiguration)
51
-
52
- let coreConfiguration = self.buildSDKConfiguration(configuration: sdkConfiguration)
53
- DatadogSDKWrapper.shared.initialize(
54
- coreConfiguration: coreConfiguration,
55
- loggerConfiguration: DatadogLogs.Logger.Configuration(sdkConfiguration),
56
- trackingConsent: sdkConfiguration.trackingConsent
57
- )
58
53
 
59
- self.enableFeatures(sdkConfiguration: sdkConfiguration)
54
+ if isCalledFromJs {
55
+ DdSdkSessionStartedListener.instance.onRnSdkInitialized()
56
+ // Handles the case in which the SDK was already initialized via initFromNative.
57
+ // Replay the current session ID so the listener can deliver it now that the
58
+ // JS-side DatadogInternalReactBridge module is guaranteed to be registered.
59
+ if DatadogSDKWrapper.shared.isInitialized() {
60
+ RUMMonitor.shared().currentSessionID { sessionId in
61
+ guard let id = sessionId else { return }
62
+ DdSdkSessionStartedListener.instance.rumSessionListener?(id, false)
63
+ }
64
+ }
65
+ }
60
66
  }
61
-
67
+
62
68
  internal func getConfigurationFromJSONFile() -> DdSdkConfiguration? {
63
69
  if let jsonResult = jsonFileReader.parseResourceFile(resourcePath: "datadog-configuration") as? Dictionary<String, AnyObject> {
64
70
  do {
@@ -75,7 +81,7 @@ public class DdSdkNativeInitialization: NSObject {
75
81
  @objc
76
82
  public func initializeFromNative() -> Void {
77
83
  if let configuration = getConfigurationFromJSONFile() {
78
- self.initialize(sdkConfiguration: configuration)
84
+ self.initialize(sdkConfiguration: configuration, isCalledFromJs: false)
79
85
  }
80
86
  }
81
87