@oodle-ai/mobile-sdk-reactnative 0.0.0-stage → 0.1.0

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 (166) hide show
  1. package/LICENSE +201 -0
  2. package/OodleMobileSdkReactNative.podspec +24 -0
  3. package/README.md +191 -2
  4. package/android/build.gradle +55 -0
  5. package/android/proguard-rules.pro +5 -0
  6. package/android/src/main/AndroidManifest.xml +4 -0
  7. package/android/src/main/java/ai/oodle/rum/Connectivity.kt +19 -0
  8. package/android/src/main/java/ai/oodle/rum/CrashReporter.kt +88 -0
  9. package/android/src/main/java/ai/oodle/rum/DeviceInfo.kt +50 -0
  10. package/android/src/main/java/ai/oodle/rum/ExitReasons.kt +104 -0
  11. package/android/src/main/java/ai/oodle/rum/NativeEvents.kt +24 -0
  12. package/android/src/main/java/ai/oodle/rum/OodleRumModule.kt +96 -0
  13. package/android/src/main/java/ai/oodle/rum/OodleRumPackage.kt +26 -0
  14. package/android/src/main/java/ai/oodle/rum/Storage.kt +84 -0
  15. package/android/src/main/java/ai/oodle/rum/Vitals.kt +188 -0
  16. package/android/src/main/java/ai/oodle/rum/Watchdog.kt +81 -0
  17. package/android/src/main/java/ai/oodle/rum/WireframeCapture.kt +398 -0
  18. package/bin/oodle-rum-upload.mjs +104 -0
  19. package/ios/OodleCrashReporter.h +16 -0
  20. package/ios/OodleCrashReporter.m +202 -0
  21. package/ios/OodleRum.h +18 -0
  22. package/ios/OodleRum.mm +129 -0
  23. package/ios/OodleRumImpl.swift +450 -0
  24. package/ios/WireframeWalker.swift +279 -0
  25. package/lib/core/clock.d.ts +19 -0
  26. package/lib/core/clock.js +47 -0
  27. package/lib/core/clock.js.map +1 -0
  28. package/lib/core/config.d.ts +142 -0
  29. package/lib/core/config.js +178 -0
  30. package/lib/core/config.js.map +1 -0
  31. package/lib/core/consent.d.ts +5 -0
  32. package/lib/core/consent.js +33 -0
  33. package/lib/core/consent.js.map +1 -0
  34. package/lib/core/context.d.ts +36 -0
  35. package/lib/core/context.js +172 -0
  36. package/lib/core/context.js.map +1 -0
  37. package/lib/core/flags.d.ts +3 -0
  38. package/lib/core/flags.js +20 -0
  39. package/lib/core/flags.js.map +1 -0
  40. package/lib/core/ids.d.ts +7 -0
  41. package/lib/core/ids.js +40 -0
  42. package/lib/core/ids.js.map +1 -0
  43. package/lib/core/internal.d.ts +6 -0
  44. package/lib/core/internal.js +10 -0
  45. package/lib/core/internal.js.map +1 -0
  46. package/lib/core/logger.d.ts +8 -0
  47. package/lib/core/logger.js +38 -0
  48. package/lib/core/logger.js.map +1 -0
  49. package/lib/core/native.d.ts +71 -0
  50. package/lib/core/native.js +156 -0
  51. package/lib/core/native.js.map +1 -0
  52. package/lib/core/rate-limiter.d.ts +7 -0
  53. package/lib/core/rate-limiter.js +31 -0
  54. package/lib/core/rate-limiter.js.map +1 -0
  55. package/lib/core/session.d.ts +51 -0
  56. package/lib/core/session.js +196 -0
  57. package/lib/core/session.js.map +1 -0
  58. package/lib/core/size.d.ts +15 -0
  59. package/lib/core/size.js +68 -0
  60. package/lib/core/size.js.map +1 -0
  61. package/lib/core/tags.d.ts +10 -0
  62. package/lib/core/tags.js +33 -0
  63. package/lib/core/tags.js.map +1 -0
  64. package/lib/core/telemetry.d.ts +6 -0
  65. package/lib/core/telemetry.js +37 -0
  66. package/lib/core/telemetry.js.map +1 -0
  67. package/lib/core/tracing.d.ts +9 -0
  68. package/lib/core/tracing.js +57 -0
  69. package/lib/core/tracing.js.map +1 -0
  70. package/lib/core/transport.d.ts +76 -0
  71. package/lib/core/transport.js +560 -0
  72. package/lib/core/transport.js.map +1 -0
  73. package/lib/core/user.d.ts +12 -0
  74. package/lib/core/user.js +41 -0
  75. package/lib/core/user.js.map +1 -0
  76. package/lib/events/actions.d.ts +13 -0
  77. package/lib/events/actions.js +147 -0
  78. package/lib/events/actions.js.map +1 -0
  79. package/lib/events/emit.d.ts +21 -0
  80. package/lib/events/emit.js +144 -0
  81. package/lib/events/emit.js.map +1 -0
  82. package/lib/events/errors.d.ts +19 -0
  83. package/lib/events/errors.js +257 -0
  84. package/lib/events/errors.js.map +1 -0
  85. package/lib/events/lifecycle.d.ts +7 -0
  86. package/lib/events/lifecycle.js +101 -0
  87. package/lib/events/lifecycle.js.map +1 -0
  88. package/lib/events/longtasks.d.ts +2 -0
  89. package/lib/events/longtasks.js +42 -0
  90. package/lib/events/longtasks.js.map +1 -0
  91. package/lib/events/resources.d.ts +15 -0
  92. package/lib/events/resources.js +156 -0
  93. package/lib/events/resources.js.map +1 -0
  94. package/lib/events/tap-target.d.ts +42 -0
  95. package/lib/events/tap-target.js +191 -0
  96. package/lib/events/tap-target.js.map +1 -0
  97. package/lib/events/view-state.d.ts +13 -0
  98. package/lib/events/view-state.js +25 -0
  99. package/lib/events/view-state.js.map +1 -0
  100. package/lib/events/views.d.ts +21 -0
  101. package/lib/events/views.js +347 -0
  102. package/lib/events/views.js.map +1 -0
  103. package/lib/index.d.ts +16 -0
  104. package/lib/index.js +24 -0
  105. package/lib/index.js.map +1 -0
  106. package/lib/navigation/react-navigation.d.ts +33 -0
  107. package/lib/navigation/react-navigation.js +61 -0
  108. package/lib/navigation/react-navigation.js.map +1 -0
  109. package/lib/react/OodlePrivacy.d.ts +15 -0
  110. package/lib/react/OodlePrivacy.js +13 -0
  111. package/lib/react/OodlePrivacy.js.map +1 -0
  112. package/lib/react/OodleProvider.d.ts +18 -0
  113. package/lib/react/OodleProvider.js +72 -0
  114. package/lib/react/OodleProvider.js.map +1 -0
  115. package/lib/replay/recorder.d.ts +22 -0
  116. package/lib/replay/recorder.js +317 -0
  117. package/lib/replay/recorder.js.map +1 -0
  118. package/lib/replay/rrweb.d.ts +105 -0
  119. package/lib/replay/rrweb.js +335 -0
  120. package/lib/replay/rrweb.js.map +1 -0
  121. package/lib/rum.d.ts +52 -0
  122. package/lib/rum.js +281 -0
  123. package/lib/rum.js.map +1 -0
  124. package/lib/specs/NativeOodleRum.d.ts +43 -0
  125. package/lib/specs/NativeOodleRum.js +5 -0
  126. package/lib/specs/NativeOodleRum.js.map +1 -0
  127. package/lib/version.d.ts +1 -0
  128. package/lib/version.js +6 -0
  129. package/lib/version.js.map +1 -0
  130. package/package.json +91 -4
  131. package/react-native.config.js +10 -0
  132. package/src/core/clock.ts +43 -0
  133. package/src/core/config.ts +344 -0
  134. package/src/core/consent.ts +32 -0
  135. package/src/core/context.ts +189 -0
  136. package/src/core/flags.ts +15 -0
  137. package/src/core/ids.ts +35 -0
  138. package/src/core/internal.ts +6 -0
  139. package/src/core/logger.ts +37 -0
  140. package/src/core/native.ts +201 -0
  141. package/src/core/rate-limiter.ts +34 -0
  142. package/src/core/session.ts +209 -0
  143. package/src/core/size.ts +79 -0
  144. package/src/core/tags.ts +30 -0
  145. package/src/core/telemetry.ts +35 -0
  146. package/src/core/tracing.ts +60 -0
  147. package/src/core/transport.ts +590 -0
  148. package/src/core/user.ts +45 -0
  149. package/src/events/actions.ts +157 -0
  150. package/src/events/emit.ts +131 -0
  151. package/src/events/errors.ts +283 -0
  152. package/src/events/lifecycle.ts +102 -0
  153. package/src/events/longtasks.ts +40 -0
  154. package/src/events/resources.ts +167 -0
  155. package/src/events/tap-target.ts +210 -0
  156. package/src/events/view-state.ts +30 -0
  157. package/src/events/views.ts +356 -0
  158. package/src/index.ts +34 -0
  159. package/src/navigation/react-navigation.ts +72 -0
  160. package/src/react/OodlePrivacy.tsx +25 -0
  161. package/src/react/OodleProvider.tsx +88 -0
  162. package/src/replay/recorder.ts +310 -0
  163. package/src/replay/rrweb.ts +460 -0
  164. package/src/rum.ts +295 -0
  165. package/src/specs/NativeOodleRum.ts +51 -0
  166. package/src/version.ts +2 -0
@@ -0,0 +1,104 @@
1
+ package ai.oodle.rum
2
+
3
+ import android.app.ActivityManager
4
+ import android.app.ApplicationExitInfo
5
+ import android.content.Context
6
+ import android.os.Build
7
+ import androidx.annotation.RequiresApi
8
+ import org.json.JSONObject
9
+
10
+ /**
11
+ * Reads why the previous process ended, from the system record. The JVM
12
+ * handler cannot see a crash in C++ code (Hermes, Fabric, native
13
+ * libraries) or an ANR that the system ended, but the system records
14
+ * both. The JS side sends the result on the next start, as a crash.
15
+ */
16
+ object ExitReasons {
17
+ /** The newest exit already handled. Older exits are never sent again. */
18
+ private const val LAST_EXIT_KEY = "last_exit_ts"
19
+ private const val MAX_TRACE_CHARS = 16_000
20
+ private const val MAX_TRACE_READ_BYTES = 256_000
21
+
22
+ fun consume(context: Context, storage: Storage): String? {
23
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return null
24
+ return consumeR(context, storage)
25
+ }
26
+
27
+ @RequiresApi(Build.VERSION_CODES.R)
28
+ private fun consumeR(context: Context, storage: Storage): String? {
29
+ val am = context.getSystemService(ActivityManager::class.java) ?: return null
30
+ val processName = context.applicationInfo.processName ?: context.packageName
31
+ val exits = am.getHistoricalProcessExitReasons(context.packageName, 0, 16).filter { it.processName == processName }
32
+ val last = storage.get(LAST_EXIT_KEY)?.toLongOrNull()
33
+ val newest = exits.maxOfOrNull { it.timestamp } ?: 0L
34
+ if (newest > (last ?: 0L)) storage.set(LAST_EXIT_KEY, newest.toString())
35
+ // On the first start with the SDK, the exits are from before the SDK
36
+ // was installed and have no session to attach to.
37
+ if (last == null) return null
38
+ val exit =
39
+ exits
40
+ .filter { it.timestamp > last }
41
+ .filter { it.reason == ApplicationExitInfo.REASON_CRASH_NATIVE || it.reason == ApplicationExitInfo.REASON_ANR }
42
+ .maxByOrNull { it.timestamp } ?: return null
43
+ return toJson(exit).toString()
44
+ }
45
+
46
+ @RequiresApi(Build.VERSION_CODES.R)
47
+ private fun toJson(exit: ApplicationExitInfo): JSONObject {
48
+ val json = JSONObject()
49
+ json.put("timestamp", exit.timestamp)
50
+ if (exit.reason == ApplicationExitInfo.REASON_ANR) {
51
+ json.put("type", "ANR")
52
+ json.put("message", exit.description?.takeIf { it.isNotBlank() } ?: "Application Not Responding: the system ended the app")
53
+ json.put("stack", mainThreadTrace(exit))
54
+ json.put("source", "anr")
55
+ } else {
56
+ val signal = signalName(exit.status)
57
+ json.put("type", signal)
58
+ json.put("message", "Native crash: $signal" + (exit.description?.takeIf { it.isNotBlank() }?.let { " ($it)" } ?: ""))
59
+ json.put("stack", "")
60
+ json.put("source", "native")
61
+ }
62
+ return json
63
+ }
64
+
65
+ /** The "main" thread block of the ANR trace, which shows where it was stuck. */
66
+ @RequiresApi(Build.VERSION_CODES.R)
67
+ private fun mainThreadTrace(exit: ApplicationExitInfo): String {
68
+ val text =
69
+ try {
70
+ exit.traceInputStream?.use { input ->
71
+ val buf = ByteArray(MAX_TRACE_READ_BYTES)
72
+ var n = 0
73
+ while (n < buf.size) {
74
+ val r = input.read(buf, n, buf.size - n)
75
+ if (r < 0) break
76
+ n += r
77
+ }
78
+ String(buf, 0, n, Charsets.UTF_8)
79
+ } ?: return ""
80
+ } catch (_: Throwable) {
81
+ return ""
82
+ }
83
+ val start = text.indexOf("\"main\"")
84
+ val block =
85
+ if (start < 0) {
86
+ text
87
+ } else {
88
+ val end = text.indexOf("\n\n", start)
89
+ if (end < 0) text.substring(start) else text.substring(start, end)
90
+ }
91
+ return if (block.length > MAX_TRACE_CHARS) block.substring(0, MAX_TRACE_CHARS) else block
92
+ }
93
+
94
+ private fun signalName(status: Int): String =
95
+ when (status) {
96
+ 4 -> "SIGILL"
97
+ 5 -> "SIGTRAP"
98
+ 6 -> "SIGABRT"
99
+ 7 -> "SIGBUS"
100
+ 8 -> "SIGFPE"
101
+ 11 -> "SIGSEGV"
102
+ else -> "Signal $status"
103
+ }
104
+ }
@@ -0,0 +1,24 @@
1
+ package ai.oodle.rum
2
+
3
+ import org.json.JSONArray
4
+ import org.json.JSONObject
5
+
6
+ /** Events found by native code (ANRs), held until JS collects them. */
7
+ object NativeEvents {
8
+ private const val MAX = 50
9
+ private val events = ArrayList<JSONObject>()
10
+
11
+ @Synchronized
12
+ fun add(event: JSONObject) {
13
+ if (events.size >= MAX) events.removeAt(0)
14
+ events.add(event)
15
+ }
16
+
17
+ @Synchronized
18
+ fun drain(): String {
19
+ val out = JSONArray()
20
+ for (e in events) out.put(e)
21
+ events.clear()
22
+ return out.toString()
23
+ }
24
+ }
@@ -0,0 +1,96 @@
1
+ package ai.oodle.rum
2
+
3
+ import com.facebook.react.bridge.LifecycleEventListener
4
+ import com.facebook.react.bridge.Promise
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.bridge.UiThreadUtil
7
+ import org.json.JSONObject
8
+
9
+ /**
10
+ * Native half of the SDK. Every method returns a fallback instead of
11
+ * throwing: a failure in monitoring code must never reach the app.
12
+ */
13
+ class OodleRumModule(reactContext: ReactApplicationContext) :
14
+ NativeOodleRumSpec(reactContext), LifecycleEventListener {
15
+ private val storage = Storage(reactContext)
16
+
17
+ init {
18
+ reactContext.addLifecycleEventListener(this)
19
+ }
20
+
21
+ override fun onHostResume() {
22
+ Vitals.resume()
23
+ Watchdog.resume()
24
+ }
25
+
26
+ override fun onHostPause() {
27
+ Vitals.pause()
28
+ Watchdog.pause()
29
+ }
30
+
31
+ override fun onHostDestroy() {
32
+ Vitals.pause()
33
+ Watchdog.pause()
34
+ }
35
+
36
+ override fun invalidate() {
37
+ reactApplicationContext.removeLifecycleEventListener(this)
38
+ super.invalidate()
39
+ }
40
+
41
+ override fun getName(): String = NAME
42
+
43
+ override fun getDeviceInfo(): String =
44
+ safe("{}") { DeviceInfo.collect(reactApplicationContext).toString() }
45
+
46
+ override fun storageGet(key: String): String? = safe(null) { storage.get(key) }
47
+
48
+ override fun storageSet(key: String, value: String): Boolean = safe(false) { storage.set(key, value) }
49
+
50
+ override fun storageSetAsync(key: String, value: String, promise: Promise) {
51
+ try {
52
+ storage.setAsync(key, value) { ok -> promise.resolve(ok) }
53
+ } catch (t: Throwable) {
54
+ promise.resolve(false)
55
+ }
56
+ }
57
+
58
+ override fun storageRemove(key: String): Boolean = safe(false) { storage.remove(key) }
59
+
60
+ override fun enableCrashReporting(): Boolean =
61
+ safe(false) { CrashReporter.install(reactApplicationContext, storage) }
62
+
63
+ override fun consumePendingCrash(): String? = safe(null) { CrashReporter.consume(reactApplicationContext, storage) }
64
+
65
+ override fun startWatchdog(thresholdMs: Double): Boolean = safe(false) { Watchdog.start(thresholdMs.toLong()) }
66
+
67
+ override fun drainNativeEvents(): String = safe("[]") { NativeEvents.drain() }
68
+
69
+ override fun startVitals(): Boolean = safe(false) { Vitals.start(reactApplicationContext) }
70
+
71
+ override fun collectVitals(): String = safe("{}") { Vitals.collect() }
72
+
73
+ override fun getConnectivity(): String = safe("unknown") { Connectivity.current(reactApplicationContext) }
74
+
75
+ override fun captureWireframes(optionsJson: String, promise: Promise) {
76
+ val options = safe(JSONObject()) { JSONObject(optionsJson) }
77
+ UiThreadUtil.runOnUiThread {
78
+ try {
79
+ promise.resolve(WireframeCapture.capture(reactApplicationContext.currentActivity, options))
80
+ } catch (t: Throwable) {
81
+ promise.reject("capture_failed", t.message ?: t.javaClass.name, t)
82
+ }
83
+ }
84
+ }
85
+
86
+ private inline fun <T> safe(fallback: T, block: () -> T): T =
87
+ try {
88
+ block()
89
+ } catch (t: Throwable) {
90
+ fallback
91
+ }
92
+
93
+ companion object {
94
+ const val NAME = "OodleRum"
95
+ }
96
+ }
@@ -0,0 +1,26 @@
1
+ package ai.oodle.rum
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+
9
+ class OodleRumPackage : BaseReactPackage() {
10
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
11
+ if (name == OodleRumModule.NAME) OodleRumModule(reactContext) else null
12
+
13
+ override fun getReactModuleInfoProvider(): ReactModuleInfoProvider = ReactModuleInfoProvider {
14
+ mapOf(
15
+ OodleRumModule.NAME to
16
+ ReactModuleInfo(
17
+ OodleRumModule.NAME,
18
+ OodleRumModule::class.java.name,
19
+ false, // canOverrideExistingModule
20
+ false, // needsEagerInit
21
+ false, // isCxxModule
22
+ true, // isTurboModule
23
+ ),
24
+ )
25
+ }
26
+ }
@@ -0,0 +1,84 @@
1
+ package ai.oodle.rum
2
+
3
+ import android.content.Context
4
+ import java.io.File
5
+ import java.util.concurrent.Executors
6
+
7
+ /**
8
+ * Small key-value files for SDK state (session, unsent events). Writes go
9
+ * through a temporary file and a rename, so a process that dies mid-write
10
+ * leaves the previous value instead of a torn one.
11
+ *
12
+ * Every write takes a version number for its key. A background write
13
+ * that is older than the last write of its key is skipped, so a
14
+ * synchronous write on the fatal error path is never replaced by an
15
+ * older background write.
16
+ */
17
+ class Storage(context: Context) {
18
+ private val dir = File(context.filesDir, DIR).apply { mkdirs() }
19
+
20
+ private fun file(key: String) = File(dir, key.replace(Regex("[^A-Za-z0-9_.-]"), "_"))
21
+
22
+ fun get(key: String): String? =
23
+ synchronized(LOCK) {
24
+ val f = file(key)
25
+ if (f.exists()) f.readText(Charsets.UTF_8) else null
26
+ }
27
+
28
+ fun set(key: String, value: String): Boolean =
29
+ synchronized(LOCK) {
30
+ bump(key)
31
+ write(key, value)
32
+ }
33
+
34
+ /** Writes on a background thread. [done] gets the result on that thread. */
35
+ fun setAsync(key: String, value: String, done: (Boolean) -> Unit) {
36
+ val version = synchronized(LOCK) { bump(key) }
37
+ EXECUTOR.execute {
38
+ val ok =
39
+ try {
40
+ synchronized(LOCK) { if (VERSIONS[versionKey(key)] != version) true else write(key, value) }
41
+ } catch (_: Throwable) {
42
+ false
43
+ }
44
+ done(ok)
45
+ }
46
+ }
47
+
48
+ fun remove(key: String): Boolean =
49
+ synchronized(LOCK) {
50
+ bump(key)
51
+ file(key).delete()
52
+ }
53
+
54
+ fun modifiedAt(key: String): Long = file(key).let { if (it.exists()) it.lastModified() else 0L }
55
+
56
+ private fun versionKey(key: String) = file(key).path
57
+
58
+ private fun bump(key: String): Long {
59
+ val k = versionKey(key)
60
+ val next = (VERSIONS[k] ?: 0L) + 1
61
+ VERSIONS[k] = next
62
+ return next
63
+ }
64
+
65
+ private fun write(key: String, value: String): Boolean {
66
+ val target = file(key)
67
+ val tmp = File(dir, target.name + ".tmp")
68
+ tmp.writeText(value, Charsets.UTF_8)
69
+ return tmp.renameTo(target) || run {
70
+ target.delete()
71
+ tmp.renameTo(target)
72
+ }
73
+ }
74
+
75
+ companion object {
76
+ const val DIR = "oodle-rum"
77
+ // Shared by all instances: the crash handler and the module can hold
78
+ // different Storage objects for the same files.
79
+ private val LOCK = Any()
80
+ private val VERSIONS = HashMap<String, Long>()
81
+ private val EXECUTOR =
82
+ Executors.newSingleThreadExecutor { r -> Thread(r, "oodle-rum-storage").apply { isDaemon = true } }
83
+ }
84
+ }
@@ -0,0 +1,188 @@
1
+ package ai.oodle.rum
2
+
3
+ import android.content.Context
4
+ import android.hardware.display.DisplayManager
5
+ import android.os.Handler
6
+ import android.os.HandlerThread
7
+ import android.os.SystemClock
8
+ import android.system.Os
9
+ import android.system.OsConstants
10
+ import android.view.Choreographer
11
+ import android.view.Display
12
+ import com.facebook.react.bridge.UiThreadUtil
13
+ import org.json.JSONObject
14
+ import java.io.File
15
+
16
+ /**
17
+ * Frame, memory and CPU statistics for the time since the last collect().
18
+ * The JS side collects at view boundaries, so each view gets its own.
19
+ */
20
+ object Vitals {
21
+ /** A gap this long between frames is a frozen frame. */
22
+ private const val FROZEN_NS = 700_000_000L
23
+ /** Longer gaps mean the app was not drawing at all (background, sleep). */
24
+ private const val PAUSE_NS = 5_000_000_000L
25
+ private const val MEMORY_SAMPLE_MS = 1000L
26
+
27
+ private val lock = Any()
28
+ private var started = false
29
+ private var expectedFrameNs = 16_666_667L
30
+ private var lastFrameNs = 0L
31
+ private var frames = 0L
32
+ private var frameNsSum = 0L
33
+ private var slow = 0
34
+ private var frozen = 0
35
+ private var windowStartNs = 0L
36
+ private var windowFrames = 0
37
+ private var minFps = 0.0
38
+ private var memSum = 0.0
39
+ private var memSamples = 0
40
+ private var memMax = 0L
41
+ private var intervalStartMs = 0L
42
+ private var cpuStartTicks = -1L
43
+ private var sampler: Handler? = null
44
+
45
+ private val frameCallback =
46
+ object : Choreographer.FrameCallback {
47
+ override fun doFrame(frameTimeNanos: Long) {
48
+ onFrame(frameTimeNanos)
49
+ Choreographer.getInstance().postFrameCallback(this)
50
+ }
51
+ }
52
+
53
+ fun start(context: Context): Boolean {
54
+ synchronized(lock) {
55
+ if (started) return true
56
+ started = true
57
+ intervalStartMs = SystemClock.uptimeMillis()
58
+ cpuStartTicks = cpuTicks()
59
+ }
60
+ try {
61
+ val dm = context.getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager
62
+ val rate = dm?.getDisplay(Display.DEFAULT_DISPLAY)?.refreshRate ?: 60f
63
+ if (rate > 1f) expectedFrameNs = (1_000_000_000L / rate).toLong()
64
+ } catch (_: Throwable) {
65
+ }
66
+ UiThreadUtil.runOnUiThread { Choreographer.getInstance().postFrameCallback(frameCallback) }
67
+ val ht = HandlerThread("oodle-rum-vitals").apply { start() }
68
+ val h = Handler(ht.looper)
69
+ sampler = h
70
+ h.post(
71
+ object : Runnable {
72
+ override fun run() {
73
+ sampleMemory()
74
+ h.postDelayed(this, MEMORY_SAMPLE_MS)
75
+ }
76
+ },
77
+ )
78
+ return true
79
+ }
80
+
81
+ /** No frames are drawn in the background; the callback would only wake the CPU. */
82
+ fun pause() {
83
+ UiThreadUtil.runOnUiThread {
84
+ Choreographer.getInstance().removeFrameCallback(frameCallback)
85
+ synchronized(lock) { lastFrameNs = 0L }
86
+ }
87
+ }
88
+
89
+ fun resume() {
90
+ synchronized(lock) { if (!started) return }
91
+ UiThreadUtil.runOnUiThread {
92
+ Choreographer.getInstance().removeFrameCallback(frameCallback)
93
+ Choreographer.getInstance().postFrameCallback(frameCallback)
94
+ }
95
+ }
96
+
97
+ private fun onFrame(nowNs: Long) {
98
+ synchronized(lock) {
99
+ val last = lastFrameNs
100
+ lastFrameNs = nowNs
101
+ if (last == 0L) {
102
+ windowStartNs = nowNs
103
+ return
104
+ }
105
+ val delta = nowNs - last
106
+ if (delta <= 0 || delta > PAUSE_NS) {
107
+ windowStartNs = nowNs
108
+ windowFrames = 0
109
+ return
110
+ }
111
+ frames++
112
+ frameNsSum += delta
113
+ if (delta > FROZEN_NS) frozen++ else if (delta > expectedFrameNs * 3 / 2) slow++
114
+ windowFrames++
115
+ val windowNs = nowNs - windowStartNs
116
+ if (windowNs >= 1_000_000_000L) {
117
+ val fps = windowFrames * 1e9 / windowNs
118
+ if (minFps == 0.0 || fps < minFps) minFps = fps
119
+ windowStartNs = nowNs
120
+ windowFrames = 0
121
+ }
122
+ }
123
+ }
124
+
125
+ private fun residentBytes(): Long {
126
+ val parts = File("/proc/self/statm").readText().trim().split(Regex("\\s+"))
127
+ return parts[1].toLong() * Os.sysconf(OsConstants._SC_PAGESIZE)
128
+ }
129
+
130
+ private fun sampleMemory() {
131
+ try {
132
+ val rss = residentBytes()
133
+ synchronized(lock) {
134
+ memSum += rss.toDouble()
135
+ memSamples++
136
+ if (rss > memMax) memMax = rss
137
+ }
138
+ } catch (_: Throwable) {
139
+ }
140
+ }
141
+
142
+ /** utime + stime of this process, in clock ticks. */
143
+ private fun cpuTicks(): Long =
144
+ try {
145
+ val stat = File("/proc/self/stat").readText()
146
+ // Fields after the command name, which is in parentheses and may hold spaces.
147
+ val fields = stat.substring(stat.lastIndexOf(')') + 2).split(' ')
148
+ fields[11].toLong() + fields[12].toLong()
149
+ } catch (_: Throwable) {
150
+ -1L
151
+ }
152
+
153
+ fun collect(): String {
154
+ val json = JSONObject()
155
+ synchronized(lock) {
156
+ val now = SystemClock.uptimeMillis()
157
+ val duration = now - intervalStartMs
158
+ json.put("duration_ms", duration)
159
+ if (frames > 0 && frameNsSum > 0) {
160
+ json.put("refresh_rate_avg", frames * 1e9 / frameNsSum)
161
+ }
162
+ if (minFps > 0) json.put("refresh_rate_min", minFps)
163
+ json.put("slow_frame_count", slow)
164
+ json.put("frozen_frame_count", frozen)
165
+ if (memSamples > 0) json.put("memory_avg_bytes", (memSum / memSamples).toLong())
166
+ if (memMax > 0) json.put("memory_max_bytes", memMax)
167
+ val ticks = cpuTicks()
168
+ if (ticks >= 0 && cpuStartTicks >= 0 && duration > 0) {
169
+ val hz = Os.sysconf(OsConstants._SC_CLK_TCK).takeIf { it > 0 } ?: 100L
170
+ val cpuMs = (ticks - cpuStartTicks) * 1000.0 / hz
171
+ json.put("cpu_ms_per_sec", cpuMs * 1000.0 / duration)
172
+ }
173
+ frames = 0
174
+ frameNsSum = 0
175
+ slow = 0
176
+ frozen = 0
177
+ minFps = 0.0
178
+ windowFrames = 0
179
+ windowStartNs = lastFrameNs
180
+ memSum = 0.0
181
+ memSamples = 0
182
+ memMax = 0
183
+ intervalStartMs = now
184
+ cpuStartTicks = ticks
185
+ }
186
+ return json.toString()
187
+ }
188
+ }
@@ -0,0 +1,81 @@
1
+ package ai.oodle.rum
2
+
3
+ import android.os.Debug
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import android.os.SystemClock
7
+ import org.json.JSONObject
8
+ import java.util.concurrent.atomic.AtomicBoolean
9
+
10
+ /**
11
+ * Posts a task to the main thread and waits for it to run. A main thread
12
+ * that does not run it within the threshold is an ANR. The main thread
13
+ * stack is taken while it is still blocked, because afterwards it shows
14
+ * only where the thread is now.
15
+ */
16
+ object Watchdog {
17
+ private const val POLL_MS = 100L
18
+ private const val PAUSE_MS = 500L
19
+ private const val MAX_STACK_FRAMES = 60
20
+ @Volatile private var thread: Thread? = null
21
+ /**
22
+ * The system does not show an ANR for a stall in the background, and
23
+ * the main thread of a background app can wait for the system on
24
+ * purpose. Stalls are only recorded while the app is in the foreground.
25
+ */
26
+ @Volatile private var foreground = true
27
+
28
+ fun pause() {
29
+ foreground = false
30
+ }
31
+
32
+ fun resume() {
33
+ foreground = true
34
+ }
35
+
36
+ @Synchronized
37
+ fun start(thresholdMs: Long): Boolean {
38
+ if (thread != null) return true
39
+ val threshold = if (thresholdMs > 0) thresholdMs else 5000L
40
+ val main = Handler(Looper.getMainLooper())
41
+ val t =
42
+ Thread({
43
+ try {
44
+ while (true) {
45
+ val ran = AtomicBoolean(false)
46
+ val postedAt = SystemClock.uptimeMillis()
47
+ main.post { ran.set(true) }
48
+ var stack: String? = null
49
+ while (!ran.get()) {
50
+ Thread.sleep(POLL_MS)
51
+ val blocked = SystemClock.uptimeMillis() - postedAt
52
+ // A paused debugger blocks the main thread on purpose.
53
+ if (stack == null && blocked >= threshold && !Debug.isDebuggerConnected()) {
54
+ stack = mainStack()
55
+ }
56
+ }
57
+ if (stack != null && foreground) {
58
+ val blocked = SystemClock.uptimeMillis() - postedAt
59
+ val e = JSONObject()
60
+ e.put("type", "anr")
61
+ e.put("timestamp", System.currentTimeMillis() - blocked)
62
+ e.put("duration_ms", blocked)
63
+ e.put("stack", stack)
64
+ NativeEvents.add(e)
65
+ }
66
+ Thread.sleep(PAUSE_MS)
67
+ }
68
+ } catch (_: InterruptedException) {
69
+ // stopped
70
+ }
71
+ }, "oodle-rum-watchdog")
72
+ t.isDaemon = true
73
+ t.priority = Thread.MIN_PRIORITY
74
+ t.start()
75
+ thread = t
76
+ return true
77
+ }
78
+
79
+ private fun mainStack(): String =
80
+ Looper.getMainLooper().thread.stackTrace.take(MAX_STACK_FRAMES).joinToString("\n") { "at $it" }
81
+ }