@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,450 @@
1
+ import Darwin
2
+ import Foundation
3
+ import Network
4
+ import QuartzCore
5
+ import UIKit
6
+
7
+ /// Native half of the SDK on iOS. OodleRum.mm forwards each TurboModule
8
+ /// call here. Structured results go back to JS as JSON strings.
9
+ @objc(OodleRumImpl)
10
+ public final class OodleRumImpl: NSObject {
11
+ @objc public static let shared = OodleRumImpl()
12
+
13
+ private let directory: URL
14
+ private let events = NativeEventQueue()
15
+ private let vitals = VitalsCollector()
16
+ private var watchdog: HangWatchdog?
17
+ private let pathMonitor = NWPathMonitor()
18
+ private let lock = NSLock()
19
+ private var connection = "unknown"
20
+
21
+ override private init() {
22
+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
23
+ ?? URL(fileURLWithPath: NSTemporaryDirectory())
24
+ directory = base.appendingPathComponent("oodle-rum", isDirectory: true)
25
+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
26
+ super.init()
27
+ pathMonitor.pathUpdateHandler = { [weak self] path in
28
+ let value: String
29
+ if path.status != .satisfied {
30
+ value = "none"
31
+ } else if path.usesInterfaceType(.wifi) {
32
+ value = "wifi"
33
+ } else if path.usesInterfaceType(.cellular) {
34
+ value = "cellular"
35
+ } else if path.usesInterfaceType(.wiredEthernet) {
36
+ value = "ethernet"
37
+ } else {
38
+ value = "other"
39
+ }
40
+ self?.lock.lock()
41
+ self?.connection = value
42
+ self?.lock.unlock()
43
+ }
44
+ pathMonitor.start(queue: DispatchQueue(label: "ai.oodle.rum.network", qos: .utility))
45
+ NotificationCenter.default.addObserver(
46
+ forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: nil
47
+ ) { [weak self] _ in
48
+ self?.events.add(["type": "memory_warning", "timestamp": Self.nowMs(), "message": "Memory warning"])
49
+ }
50
+ }
51
+
52
+ static func nowMs() -> Int64 {
53
+ Int64(Date().timeIntervalSince1970 * 1000)
54
+ }
55
+
56
+ /// Keys are sorted, so the same object always gives the same text.
57
+ static func json(_ object: Any) -> String {
58
+ guard JSONSerialization.isValidJSONObject(object),
59
+ let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]),
60
+ let text = String(data: data, encoding: .utf8)
61
+ else { return "{}" }
62
+ return text
63
+ }
64
+
65
+ // MARK: Device
66
+
67
+ @objc public func storageDirectory() -> String {
68
+ directory.path
69
+ }
70
+
71
+ @objc public func deviceInfo() -> String {
72
+ let bundle = Bundle.main
73
+ let screen = UIScreen.main
74
+ var info: [String: Any] = [
75
+ "brand": "Apple",
76
+ "model": Self.modelIdentifier(),
77
+ "osName": UIDevice.current.systemName == "iPadOS" ? "iPadOS" : "iOS",
78
+ "osVersion": UIDevice.current.systemVersion,
79
+ "appVersion": bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "",
80
+ "appBuild": bundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "",
81
+ "bundleId": bundle.bundleIdentifier ?? "",
82
+ "deviceType": UIDevice.current.userInterfaceIdiom == .pad ? "tablet" : "mobile",
83
+ "screenWidth": Double(screen.bounds.width),
84
+ "screenHeight": Double(screen.bounds.height),
85
+ "scale": Double(screen.scale),
86
+ "locale": Locale.preferredLanguages.first ?? "",
87
+ ]
88
+ info["processStartMs"] = Self.processStartMs()
89
+ return Self.json(info)
90
+ }
91
+
92
+ /// "iPhone15,2". The simulator reports the model it simulates.
93
+ static func modelIdentifier() -> String {
94
+ if let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
95
+ return simulated
96
+ }
97
+ var system = utsname()
98
+ uname(&system)
99
+ let mirror = Mirror(reflecting: system.machine)
100
+ return mirror.children.reduce(into: "") { result, element in
101
+ if let value = element.value as? Int8, value != 0 {
102
+ result.append(Character(UnicodeScalar(UInt8(value))))
103
+ }
104
+ }
105
+ }
106
+
107
+ /// Wall clock time the process started, or 0 when the system started the
108
+ /// process early ("prewarming"); a start measured from then is not a
109
+ /// launch the user waited for.
110
+ static func processStartMs() -> Double {
111
+ if ProcessInfo.processInfo.environment["ActivePrewarm"] == "1" { return 0 }
112
+ var kinfo = kinfo_proc()
113
+ var size = MemoryLayout<kinfo_proc>.stride
114
+ var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
115
+ guard sysctl(&mib, u_int(mib.count), &kinfo, &size, nil, 0) == 0 else { return 0 }
116
+ let start = kinfo.kp_proc.p_un.__p_starttime
117
+ return Double(start.tv_sec) * 1000 + Double(start.tv_usec) / 1000
118
+ }
119
+
120
+ // MARK: Storage
121
+
122
+ private func fileURL(_ key: String) -> URL {
123
+ let safe = String(key.map { $0.isLetter || $0.isNumber || $0 == "_" || $0 == "." || $0 == "-" ? $0 : "_" })
124
+ return directory.appendingPathComponent(safe)
125
+ }
126
+
127
+ // Every write takes a version number for its key. A background write
128
+ // that is older than the last write of its key is skipped, so a
129
+ // synchronous write on the fatal error path is never replaced by an
130
+ // older background write.
131
+ private let storageLock = NSLock()
132
+ private var storageVersions: [String: Int] = [:]
133
+ private let storageQueue = DispatchQueue(label: "ai.oodle.rum.storage", qos: .utility)
134
+
135
+ private func bumpVersion(_ key: String) -> Int {
136
+ let next = (storageVersions[key] ?? 0) + 1
137
+ storageVersions[key] = next
138
+ return next
139
+ }
140
+
141
+ private func write(_ key: String, _ value: String) -> Bool {
142
+ do {
143
+ try value.write(to: fileURL(key), atomically: true, encoding: .utf8)
144
+ return true
145
+ } catch {
146
+ return false
147
+ }
148
+ }
149
+
150
+ @objc public func storageGet(_ key: String) -> String? {
151
+ storageLock.lock()
152
+ defer { storageLock.unlock() }
153
+ return try? String(contentsOf: fileURL(key), encoding: .utf8)
154
+ }
155
+
156
+ @objc public func storageSet(_ key: String, value: String) -> Bool {
157
+ storageLock.lock()
158
+ defer { storageLock.unlock() }
159
+ _ = bumpVersion(key)
160
+ return write(key, value)
161
+ }
162
+
163
+ /// Writes on a background queue and calls `done` there.
164
+ @objc public func storageSetAsync(_ key: String, value: String, done: @escaping (Bool) -> Void) {
165
+ storageLock.lock()
166
+ let version = bumpVersion(key)
167
+ storageLock.unlock()
168
+ storageQueue.async { [weak self] in
169
+ guard let self = self else { return done(false) }
170
+ self.storageLock.lock()
171
+ let ok = self.storageVersions[key] == version ? self.write(key, value) : true
172
+ self.storageLock.unlock()
173
+ done(ok)
174
+ }
175
+ }
176
+
177
+ @objc public func storageRemove(_ key: String) -> Bool {
178
+ storageLock.lock()
179
+ defer { storageLock.unlock() }
180
+ _ = bumpVersion(key)
181
+ return (try? FileManager.default.removeItem(at: fileURL(key))) != nil
182
+ }
183
+
184
+ // MARK: Watchdog, vitals, connectivity
185
+
186
+ @objc public func startWatchdog(_ thresholdMs: Double) -> Bool {
187
+ lock.lock()
188
+ defer { lock.unlock() }
189
+ if watchdog == nil {
190
+ let w = HangWatchdog(thresholdMs: thresholdMs > 0 ? thresholdMs : 2000, events: events)
191
+ w.start()
192
+ watchdog = w
193
+ }
194
+ return true
195
+ }
196
+
197
+ @objc public func drainNativeEvents() -> String {
198
+ events.drain()
199
+ }
200
+
201
+ @objc public func startVitals() -> Bool {
202
+ vitals.start()
203
+ return true
204
+ }
205
+
206
+ @objc public func collectVitals() -> String {
207
+ Self.json(vitals.collect())
208
+ }
209
+
210
+ @objc public func connectivity() -> String {
211
+ lock.lock()
212
+ defer { lock.unlock() }
213
+ return connection
214
+ }
215
+
216
+ // MARK: Replay
217
+
218
+ /// The last walk result. Read and written on the main thread only.
219
+ private var lastCapture: String?
220
+
221
+ /// Must run on the main thread. With `skipUnchanged`, a walk that gives
222
+ /// the same result as the last one returns a short marker, so the JS
223
+ /// side does not parse and compare the same screen again.
224
+ @objc public func captureWireframes(_ optionsJson: String) -> String {
225
+ var maxNodes = 2000
226
+ var skipUnchanged = false
227
+ if let data = optionsJson.data(using: .utf8),
228
+ let options = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
229
+ if let n = options["maxNodes"] as? Int { maxNodes = n }
230
+ skipUnchanged = (options["skipUnchanged"] as? Bool) ?? false
231
+ }
232
+ let result = Self.json(WireframeWalker(maxNodes: maxNodes).capture())
233
+ if skipUnchanged && result == lastCapture {
234
+ return "{\"unchanged\":true}"
235
+ }
236
+ lastCapture = result
237
+ return result
238
+ }
239
+ }
240
+
241
+ // MARK: - Native events
242
+
243
+ final class NativeEventQueue {
244
+ private let lock = NSLock()
245
+ private var items: [[String: Any]] = []
246
+ private let max = 50
247
+
248
+ func add(_ event: [String: Any]) {
249
+ lock.lock()
250
+ if items.count >= max { items.removeFirst() }
251
+ items.append(event)
252
+ lock.unlock()
253
+ }
254
+
255
+ func drain() -> String {
256
+ lock.lock()
257
+ let out = items
258
+ items.removeAll()
259
+ lock.unlock()
260
+ guard JSONSerialization.isValidJSONObject(out),
261
+ let data = try? JSONSerialization.data(withJSONObject: out)
262
+ else { return "[]" }
263
+ return String(data: data, encoding: .utf8) ?? "[]"
264
+ }
265
+ }
266
+
267
+ // MARK: - Hang watchdog
268
+
269
+ /// Sends a block to the main queue and waits for it to run. A main thread
270
+ /// that does not run it within the threshold is a hang.
271
+ final class HangWatchdog {
272
+ private let thresholdMs: Double
273
+ private let events: NativeEventQueue
274
+ private var thread: Thread?
275
+
276
+ init(thresholdMs: Double, events: NativeEventQueue) {
277
+ self.thresholdMs = thresholdMs
278
+ self.events = events
279
+ }
280
+
281
+ func start() {
282
+ let t = Thread { [weak self] in self?.run() }
283
+ t.name = "oodle-rum-watchdog"
284
+ t.qualityOfService = .utility
285
+ t.start()
286
+ thread = t
287
+ }
288
+
289
+ private func run() {
290
+ while true {
291
+ let semaphore = DispatchSemaphore(value: 0)
292
+ let postedAt = CACurrentMediaTime()
293
+ DispatchQueue.main.async { semaphore.signal() }
294
+ if semaphore.wait(timeout: .now() + .milliseconds(Int(thresholdMs))) == .timedOut {
295
+ // Still blocked: wait for the end so the event has the full duration.
296
+ semaphore.wait()
297
+ let blockedMs = (CACurrentMediaTime() - postedAt) * 1000
298
+ events.add([
299
+ "type": "app_hang",
300
+ "timestamp": OodleRumImpl.nowMs() - Int64(blockedMs),
301
+ "duration_ms": Int64(blockedMs),
302
+ ])
303
+ }
304
+ Thread.sleep(forTimeInterval: 0.5)
305
+ }
306
+ }
307
+ }
308
+
309
+ // MARK: - Vitals
310
+
311
+ /// Frame, memory and CPU statistics since the last collect().
312
+ final class VitalsCollector: NSObject {
313
+ private static let frozenSeconds = 0.7
314
+ private static let pauseSeconds = 5.0
315
+
316
+ private let lock = NSLock()
317
+ private var link: CADisplayLink?
318
+ private var timer: DispatchSourceTimer?
319
+ private var lastFrame: CFTimeInterval = 0
320
+ private var frames = 0
321
+ private var frameTime: Double = 0
322
+ private var slow = 0
323
+ private var frozen = 0
324
+ private var windowStart: CFTimeInterval = 0
325
+ private var windowFrames = 0
326
+ private var minFps: Double = 0
327
+ private var memSum: Double = 0
328
+ private var memSamples = 0
329
+ private var memMax: UInt64 = 0
330
+ private var intervalStart = CACurrentMediaTime()
331
+ private var cpuStart = VitalsCollector.cpuSeconds()
332
+
333
+ func start() {
334
+ DispatchQueue.main.async {
335
+ guard self.link == nil else { return }
336
+ let link = CADisplayLink(target: self, selector: #selector(self.onFrame(_:)))
337
+ link.add(to: .main, forMode: .common)
338
+ self.link = link
339
+ let center = NotificationCenter.default
340
+ center.addObserver(self, selector: #selector(self.pause), name: UIApplication.didEnterBackgroundNotification, object: nil)
341
+ center.addObserver(self, selector: #selector(self.resume), name: UIApplication.willEnterForegroundNotification, object: nil)
342
+ }
343
+ let t = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .utility))
344
+ t.schedule(deadline: .now(), repeating: 1.0)
345
+ t.setEventHandler { [weak self] in self?.sampleMemory() }
346
+ t.resume()
347
+ timer = t
348
+ }
349
+
350
+ @objc private func pause() {
351
+ link?.isPaused = true
352
+ lock.lock()
353
+ lastFrame = 0
354
+ lock.unlock()
355
+ }
356
+
357
+ @objc private func resume() {
358
+ link?.isPaused = false
359
+ }
360
+
361
+ @objc private func onFrame(_ link: CADisplayLink) {
362
+ let now = link.timestamp
363
+ let expected = max(link.targetTimestamp - link.timestamp, 1.0 / 120.0)
364
+ lock.lock()
365
+ defer { lock.unlock() }
366
+ let last = lastFrame
367
+ lastFrame = now
368
+ if last == 0 {
369
+ windowStart = now
370
+ return
371
+ }
372
+ let delta = now - last
373
+ if delta <= 0 || delta > Self.pauseSeconds {
374
+ windowStart = now
375
+ windowFrames = 0
376
+ return
377
+ }
378
+ frames += 1
379
+ frameTime += delta
380
+ if delta > Self.frozenSeconds {
381
+ frozen += 1
382
+ } else if delta > expected * 1.5 {
383
+ slow += 1
384
+ }
385
+ windowFrames += 1
386
+ if now - windowStart >= 1.0 {
387
+ let fps = Double(windowFrames) / (now - windowStart)
388
+ if minFps == 0 || fps < minFps { minFps = fps }
389
+ windowStart = now
390
+ windowFrames = 0
391
+ }
392
+ }
393
+
394
+ private func sampleMemory() {
395
+ var info = task_vm_info_data_t()
396
+ var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)
397
+ let result = withUnsafeMutablePointer(to: &info) {
398
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
399
+ task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
400
+ }
401
+ }
402
+ guard result == KERN_SUCCESS else { return }
403
+ let footprint = info.phys_footprint
404
+ lock.lock()
405
+ memSum += Double(footprint)
406
+ memSamples += 1
407
+ if footprint > memMax { memMax = footprint }
408
+ lock.unlock()
409
+ }
410
+
411
+ /// User plus system CPU time of this process.
412
+ static func cpuSeconds() -> Double {
413
+ var usage = rusage()
414
+ guard getrusage(RUSAGE_SELF, &usage) == 0 else { return -1 }
415
+ let user = Double(usage.ru_utime.tv_sec) + Double(usage.ru_utime.tv_usec) / 1_000_000
416
+ let system = Double(usage.ru_stime.tv_sec) + Double(usage.ru_stime.tv_usec) / 1_000_000
417
+ return user + system
418
+ }
419
+
420
+ func collect() -> [String: Any] {
421
+ lock.lock()
422
+ defer { lock.unlock() }
423
+ let now = CACurrentMediaTime()
424
+ let duration = now - intervalStart
425
+ var out: [String: Any] = ["duration_ms": Int64(duration * 1000)]
426
+ if frames > 0, frameTime > 0 { out["refresh_rate_avg"] = Double(frames) / frameTime }
427
+ if minFps > 0 { out["refresh_rate_min"] = minFps }
428
+ out["slow_frame_count"] = slow
429
+ out["frozen_frame_count"] = frozen
430
+ if memSamples > 0 { out["memory_avg_bytes"] = Int64(memSum / Double(memSamples)) }
431
+ if memMax > 0 { out["memory_max_bytes"] = Int64(memMax) }
432
+ let cpu = Self.cpuSeconds()
433
+ if cpu >= 0, cpuStart >= 0, duration > 0 {
434
+ out["cpu_ms_per_sec"] = (cpu - cpuStart) * 1000 / duration
435
+ }
436
+ frames = 0
437
+ frameTime = 0
438
+ slow = 0
439
+ frozen = 0
440
+ minFps = 0
441
+ windowFrames = 0
442
+ windowStart = lastFrame
443
+ memSum = 0
444
+ memSamples = 0
445
+ memMax = 0
446
+ intervalStart = now
447
+ cpuStart = cpu
448
+ return out
449
+ }
450
+ }