@libo11y/react-native 0.4.0 → 0.7.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.
@@ -65,7 +65,7 @@ export async function openStorageQueue(opts) {
65
65
  // say) is dropped after MAX_READ_FAILURES, so it cannot hold the queue up for its whole age.
66
66
  const readFailures = new Map();
67
67
  let chain = Promise.resolve();
68
- const serial = (fallback, fn) => {
68
+ const serial = (fallback, fn, requireSuccess) => {
69
69
  const run = async () => {
70
70
  if (closed)
71
71
  return fallback;
@@ -74,6 +74,8 @@ export async function openStorageQueue(opts) {
74
74
  }
75
75
  catch (err) {
76
76
  diag.warn("libo11y: react-native: a retry queue operation failed", err);
77
+ if (requireSuccess)
78
+ throw err;
77
79
  return fallback;
78
80
  }
79
81
  };
@@ -99,10 +101,9 @@ export async function openStorageQueue(opts) {
99
101
  })),
100
102
  }));
101
103
  };
102
- // Removes the bodies no entry owns, once per queue (and again after clear). Best effort: an
103
- // orphan that cannot be listed or removed waits for the next launch, and never fails the put or
104
- // claim that ran the cleanup.
105
- const cleanup = async () => {
104
+ // Removes bodies no entry owns, once per queue and again after clear. Only a strict clear fails
105
+ // when storage cannot list or remove them.
106
+ const cleanup = async (requireSuccess) => {
106
107
  if (cleaned || closed)
107
108
  return;
108
109
  cleaned = true;
@@ -111,12 +112,20 @@ export async function openStorageQueue(opts) {
111
112
  keys = await storage.getAllKeys();
112
113
  }
113
114
  catch (err) {
115
+ if (requireSuccess) {
116
+ cleaned = false;
117
+ throw err;
118
+ }
114
119
  diag.warn("libo11y: react-native: listing the retry queue's orphans failed", err);
115
120
  return;
116
121
  }
117
122
  for (const key of keys) {
118
123
  if (key.startsWith(bodyPrefix) && !entries.has(key.slice(bodyPrefix.length))) {
119
124
  await storage.removeItem(key).catch((err) => {
125
+ if (requireSuccess) {
126
+ cleaned = false;
127
+ throw err;
128
+ }
120
129
  diag.warn("libo11y: react-native: removing an orphan of the retry queue failed", err);
121
130
  });
122
131
  }
@@ -155,7 +164,7 @@ export async function openStorageQueue(opts) {
155
164
  }
156
165
  return entry;
157
166
  }),
158
- claim: (now, limit, leaseMillis) => serial([], async () => {
167
+ claim: (now, limit, leaseMillis, match) => serial([], async () => {
159
168
  await cleanup();
160
169
  const out = [];
161
170
  const gone = [];
@@ -185,6 +194,9 @@ export async function openStorageQueue(opts) {
185
194
  gone.push(e.id);
186
195
  continue;
187
196
  }
197
+ // Checked with the body read and before the lease, so a refused entry stays claimable.
198
+ if (match !== undefined && !match({ ...e, body }))
199
+ continue;
188
200
  const leased = { ...e, leaseUntil: now + leaseMillis };
189
201
  entries.set(e.id, leased);
190
202
  out.push({ ...leased, body });
@@ -209,13 +221,13 @@ export async function openStorageQueue(opts) {
209
221
  await drop(known);
210
222
  await writeIndex();
211
223
  }),
212
- clear: () => serial(undefined, async () => {
224
+ clear: (requireSuccess) => serial(undefined, async () => {
213
225
  entries.clear();
214
226
  readFailures.clear();
215
227
  cleaned = false;
216
228
  await storage.removeItem(indexKey);
217
- await cleanup();
218
- }),
229
+ await cleanup(requireSuccess);
230
+ }, requireSuccess),
219
231
  releaseLeases: () => serial(undefined, async () => {
220
232
  for (const [id, e] of entries)
221
233
  if (e.leaseUntil !== 0)
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The `@libo11y/react-native` package version. scripts/release.ts keeps it equal to package.json. */
2
- export declare const VERSION = "0.4.0";
2
+ export declare const VERSION = "0.7.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The `@libo11y/react-native` package version. scripts/release.ts keeps it equal to package.json. */
2
- export const VERSION = "0.4.0";
2
+ export const VERSION = "0.7.0";
@@ -0,0 +1,6 @@
1
+ {
2
+ "platforms": ["apple"],
3
+ "apple": {
4
+ "modules": ["Libo11yNativeModule"]
5
+ }
6
+ }
@@ -0,0 +1,435 @@
1
+ import CryptoKit
2
+ import Foundation
3
+ import MetricKit
4
+
5
+ /// Keeps MetricKit's crash and hang reports, and the history of what JavaScript said was current,
6
+ /// under Application Support/libo11y:
7
+ ///
8
+ /// - `recording`: present while RUM records under consent, holding when recording was switched on
9
+ /// (epoch milliseconds). Without it, reports are dropped as they arrive, and so is a report whose
10
+ /// payload ended before that time. A report is kept only when it names its process (iOS 17 and
11
+ /// later) and `context.json` holds an entry that process wrote at or before the payload began,
12
+ /// which it does only while RUM records under consent; any other report is dropped, because
13
+ /// nothing shows its process had consent for the whole window it may have happened in. Switching it off also deletes the reports, the history and the tombstones.
14
+ /// - `acknowledged.json`: the IDs of the reports JavaScript acknowledged in the last 8 days, so a
15
+ /// report MetricKit delivers again (pastDiagnosticPayloads) is not kept twice.
16
+ /// - `diagnostics/<id>.json`: one file per report, id the SHA-256 of MetricKit's JSON for it and of
17
+ /// where it was in its payload (the payload's time range, the report's kind and index), so a
18
+ /// report delivered twice is kept once and two reports alike are kept apart. At most 32, none
19
+ /// older than 7 days.
20
+ /// - `context.json`: the last 64 context entries JavaScript wrote, each with this process's ID,
21
+ /// start time and first consented write added, so a report from an earlier launch maps to the
22
+ /// session and screen it happened in, and its process's consent outlasts its first entry.
23
+ /// - `cleanup-pending`: present while a cleanup has not deleted everything. The module then keeps
24
+ /// and reads back nothing, and recording cannot be switched on until a retried cleanup succeeds.
25
+ ///
26
+ /// Every file operation runs on one serial queue, and none of them on the JavaScript thread.
27
+ final class Libo11yDiagnostics: NSObject, MXMetricManagerSubscriber {
28
+ static let shared = Libo11yDiagnostics()
29
+
30
+ private static let maxReports = 32
31
+ private static let maxHistory = 64
32
+ private static let maxAge: TimeInterval = 7 * 24 * 60 * 60
33
+ private static let maxTombstones = 256
34
+ private static let tombstoneAge: Double = 8 * 24 * 60 * 60 * 1000
35
+ /// What a cleanup that could not write its marker leaves in the flag, so it holds no time.
36
+ private static let invalidFlag = "cleanup-pending"
37
+ /// How far after its payload ended a process may have started and still be the report's.
38
+ private static let slackMillis: Double = 60_000
39
+ /// At most this many bytes of reports go to JavaScript in one call; the rest wait for the next.
40
+ private static let maxBatchBytes = 512 * 1024
41
+
42
+ private let queue = DispatchQueue(label: "ing.o11y.libo11y.diagnostics")
43
+ private var started = false
44
+ /// Set by setRecording(false): this process keeps nothing more, even when deleting the flag
45
+ /// failed. A later setRecording(true) clears it.
46
+ private var off = false
47
+ /// When this process first wrote context under consent, epoch milliseconds, stamped on every
48
+ /// entry it writes so the time outlasts that first entry in the rolling history. Cleared by
49
+ /// setRecording(false).
50
+ private var consentSince: Double?
51
+ private let fm = FileManager.default
52
+
53
+ private lazy var root: URL? = fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?
54
+ .appendingPathComponent("libo11y", isDirectory: true)
55
+ private var reportsDir: URL? { root?.appendingPathComponent("diagnostics", isDirectory: true) }
56
+ private var historyFile: URL? { root?.appendingPathComponent("context.json", isDirectory: false) }
57
+ private var recordingFile: URL? { root?.appendingPathComponent("recording", isDirectory: false) }
58
+ private var tombstoneFile: URL? { root?.appendingPathComponent("acknowledged.json", isDirectory: false) }
59
+ /// Present from the start of a cleanup until it deleted everything. While it is, the module
60
+ /// keeps nothing, reads nothing back, and cannot be switched on before the cleanup succeeds.
61
+ private var cleanupFile: URL? { root?.appendingPathComponent("cleanup-pending", isDirectory: false) }
62
+
63
+ /// Subscribes to MetricKit once per process and keeps the reports it delivered before this.
64
+ func start() {
65
+ let first: Bool = queue.sync {
66
+ if started { return false }
67
+ started = true
68
+ return true
69
+ }
70
+ guard first else { return }
71
+ MXMetricManager.shared.add(self)
72
+ // Reading the payloads MetricKit delivered earlier parses them, so it runs on the queue, not on
73
+ // the thread that creates the module.
74
+ queue.async { [self] in
75
+ storeOnQueue(MXMetricManager.shared.pastDiagnosticPayloads)
76
+ }
77
+ }
78
+
79
+ // MARK: MXMetricManagerSubscriber
80
+
81
+ func didReceive(_ payloads: [MXDiagnosticPayload]) {
82
+ store(payloads)
83
+ }
84
+
85
+ // MARK: JavaScript
86
+
87
+ /// Runs on the module's async function queue, not the JavaScript thread, and returns once done,
88
+ /// so JavaScript can wait for the deletion a revoke needs. Off throws when a file could not be
89
+ /// deleted; the module records nothing more in this process anyway, keeps the cleanup pending on
90
+ /// disk, and On throws until a cleanup it retries succeeds.
91
+ func setRecording(_ on: Bool) throws {
92
+ try queue.sync {
93
+ guard let root = root, let flag = recordingFile else { return }
94
+ if on {
95
+ // Recording that a failed delete left behind is not this consent's: finish deleting first.
96
+ if off || cleanupPending() || flagInvalid() { try cleanUp() }
97
+ off = false
98
+ try? fm.createDirectory(at: root, withIntermediateDirectories: true)
99
+ // Telemetry that waits on this device is not for a restored backup of it.
100
+ var dir = root
101
+ var values = URLResourceValues()
102
+ values.isExcludedFromBackup = true
103
+ try? dir.setResourceValues(values)
104
+ if !fm.fileExists(atPath: flag.path) {
105
+ let since = String(Date().timeIntervalSince1970 * 1000)
106
+ fm.createFile(atPath: flag.path, contents: since.data(using: .utf8))
107
+ }
108
+ } else {
109
+ off = true
110
+ consentSince = nil
111
+ try cleanUp()
112
+ }
113
+ }
114
+ }
115
+
116
+ private func cleanupPending() -> Bool {
117
+ guard let marker = cleanupFile else { return false }
118
+ return fm.fileExists(atPath: marker.path)
119
+ }
120
+
121
+ /// Deletes the flag, the reports, the history and the tombstones, with the cleanup marked pending
122
+ /// on disk until all of them are gone. Throws naming what it could not delete. Runs on the queue.
123
+ private func cleanUp() throws {
124
+ guard let root = root, let marker = cleanupFile else { return }
125
+ try? fm.createDirectory(at: root, withIntermediateDirectories: true)
126
+ // Without the marker on disk, the flag is invalidated instead, so a later launch cannot take
127
+ // it for consent and must clean up first.
128
+ if !cleanupPending(), !fm.createFile(atPath: marker.path, contents: Data()), let flag = recordingFile,
129
+ fm.fileExists(atPath: flag.path)
130
+ {
131
+ try? Data(Self.invalidFlag.utf8).write(to: flag, options: .atomic)
132
+ }
133
+ var failed: [String] = []
134
+ for url in [recordingFile, reportsDir, historyFile, tombstoneFile].compactMap({ $0 })
135
+ where fm.fileExists(atPath: url.path) {
136
+ do {
137
+ try fm.removeItem(at: url)
138
+ } catch {
139
+ failed.append(url.lastPathComponent)
140
+ }
141
+ }
142
+ if failed.isEmpty, cleanupPending() {
143
+ do {
144
+ try fm.removeItem(at: marker)
145
+ } catch {
146
+ failed.append(marker.lastPathComponent)
147
+ }
148
+ }
149
+ if !failed.isEmpty { throw CleanupFailed(files: failed) }
150
+ }
151
+
152
+ /// What setRecording(false) could not delete.
153
+ struct CleanupFailed: Error, CustomStringConvertible {
154
+ let files: [String]
155
+ var description: String { "libo11y: could not delete \(files.joined(separator: ", "))" }
156
+ }
157
+
158
+ /// Appends one entry while recording, and returns whether it did.
159
+ func recordContext(_ json: String) -> Bool {
160
+ queue.sync {
161
+ guard isRecording(), let file = historyFile,
162
+ let data = json.data(using: .utf8),
163
+ var entry = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
164
+ else { return false }
165
+ entry["pid"] = Libo11yProcess.pid
166
+ if let start = Libo11yProcess.startEpochMillis { entry["processStart"] = start }
167
+ let since = consentSince ?? (entry["at"] as? Double) ?? Date().timeIntervalSince1970 * 1000
168
+ entry["since"] = since
169
+ var history = readHistory()
170
+ history.append(entry)
171
+ if history.count > Self.maxHistory { history.removeFirst(history.count - Self.maxHistory) }
172
+ guard let out = try? JSONSerialization.data(withJSONObject: history),
173
+ (try? out.write(to: file, options: .atomic)) != nil
174
+ else { return false }
175
+ consentSince = since
176
+ return true
177
+ }
178
+ }
179
+
180
+ func contextHistory() -> String {
181
+ queue.sync {
182
+ guard !off, !cleanupPending(), let file = historyFile, let data = try? Data(contentsOf: file)
183
+ else { return "[]" }
184
+ return String(data: data, encoding: .utf8) ?? "[]"
185
+ }
186
+ }
187
+
188
+ /// The kept reports, oldest first, up to maxBatchBytes of them (always at least one).
189
+ func pendingDiagnostics() -> String {
190
+ queue.sync {
191
+ if off || cleanupPending() { return "[]" }
192
+ var reports: [[String: Any]] = []
193
+ var bytes = 0
194
+ for url in reportFiles().sorted(by: { modified($0) < modified($1) }) {
195
+ guard let data = try? Data(contentsOf: url) else { continue }
196
+ if !reports.isEmpty && bytes + data.count > Self.maxBatchBytes { break }
197
+ guard var report = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { continue }
198
+ report["id"] = url.deletingPathExtension().lastPathComponent
199
+ reports.append(report)
200
+ bytes += data.count
201
+ }
202
+ guard let out = try? JSONSerialization.data(withJSONObject: reports) else { return "[]" }
203
+ return String(data: out, encoding: .utf8) ?? "[]"
204
+ }
205
+ }
206
+
207
+ func acknowledge(_ ids: [String]) {
208
+ queue.async { [self] in
209
+ guard let dir = reportsDir else { return }
210
+ let valid = ids.filter(Self.isReportID)
211
+ for id in valid {
212
+ try? fm.removeItem(at: dir.appendingPathComponent("\(id).json", isDirectory: false))
213
+ }
214
+ guard isRecording(), let file = tombstoneFile, !valid.isEmpty else { return }
215
+ let now = Date().timeIntervalSince1970 * 1000
216
+ var tombstones = readTombstones().filter { now - $0.value < Self.tombstoneAge }
217
+ for id in valid { tombstones[id] = now }
218
+ if tombstones.count > Self.maxTombstones {
219
+ let keep = tombstones.sorted { $0.value > $1.value }.prefix(Self.maxTombstones)
220
+ tombstones = Dictionary(uniqueKeysWithValues: keep.map { ($0.key, $0.value) })
221
+ }
222
+ if let out = try? JSONSerialization.data(withJSONObject: tombstones) {
223
+ try? out.write(to: file, options: .atomic)
224
+ }
225
+ }
226
+ }
227
+
228
+ // MARK: Storage
229
+
230
+ private static func isReportID(_ id: String) -> Bool {
231
+ !id.isEmpty && id.count <= 64 && id.allSatisfy { $0.isHexDigit }
232
+ }
233
+
234
+ private func isRecording() -> Bool {
235
+ recordingSince() != nil
236
+ }
237
+
238
+ /// When recording was switched on, epoch milliseconds; nil when it is off.
239
+ private func recordingSince() -> Double? {
240
+ guard !off, !cleanupPending() else { return nil }
241
+ return flagSince()
242
+ }
243
+
244
+ /// The time the flag holds; nil when there is no flag or it holds none, as an invalidated one.
245
+ private func flagSince() -> Double? {
246
+ guard let flag = recordingFile, let data = fm.contents(atPath: flag.path) else { return nil }
247
+ return Double(String(data: data, encoding: .utf8) ?? "")
248
+ }
249
+
250
+ /// Whether a flag is there that holds no time: one a cleanup invalidated.
251
+ private func flagInvalid() -> Bool {
252
+ guard let flag = recordingFile else { return false }
253
+ return fm.fileExists(atPath: flag.path) && flagSince() == nil
254
+ }
255
+
256
+ /// The acknowledged report IDs, with when each was acknowledged.
257
+ private func readTombstones() -> [String: Double] {
258
+ guard let file = tombstoneFile, let data = try? Data(contentsOf: file),
259
+ let map = (try? JSONSerialization.jsonObject(with: data)) as? [String: Double]
260
+ else { return [:] }
261
+ return map
262
+ }
263
+
264
+ private func readHistory() -> [[String: Any]] {
265
+ guard let file = historyFile, let data = try? Data(contentsOf: file),
266
+ let list = (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]]
267
+ else { return [] }
268
+ return list
269
+ }
270
+
271
+ private func modified(_ url: URL) -> Date {
272
+ (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast
273
+ }
274
+
275
+ /// The context entries of the processes that recorded under consent, by process ID: each
276
+ /// entry's process start and the earliest its process is known to have had consent, when it was
277
+ /// written or the first consent stamped on it. An entry without a start counts as one from any
278
+ /// time.
279
+ private func consentedProcesses() -> [Int: [(start: Double, at: Double)]] {
280
+ var out: [Int: [(start: Double, at: Double)]] = [:]
281
+ for entry in readHistory() {
282
+ guard let pid = entry["pid"] as? Int, let at = entry["at"] as? Double else { continue }
283
+ let first = min(at, entry["since"] as? Double ?? at)
284
+ out[pid, default: []].append((start: entry["processStart"] as? Double ?? 0, at: first))
285
+ }
286
+ return out
287
+ }
288
+
289
+ private func reportFiles() -> [URL] {
290
+ guard let dir = reportsDir,
291
+ let urls = try? fm.contentsOfDirectory(
292
+ at: dir, includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsHiddenFiles])
293
+ else { return [] }
294
+ return urls.filter { $0.pathExtension == "json" }
295
+ }
296
+
297
+ private func store(_ payloads: [MXDiagnosticPayload]) {
298
+ guard !payloads.isEmpty else { return }
299
+ queue.async { [self] in storeOnQueue(payloads) }
300
+ }
301
+
302
+ /// Keeps the crash and hang reports of payloads. Runs on the queue.
303
+ private func storeOnQueue(_ payloads: [MXDiagnosticPayload]) {
304
+ guard !payloads.isEmpty else { return }
305
+ do {
306
+ guard let since = recordingSince(), let dir = reportsDir else { return }
307
+ try? fm.createDirectory(at: dir, withIntermediateDirectories: true)
308
+ let acknowledged = readTombstones()
309
+ let consented = consentedProcesses()
310
+ for payload in payloads {
311
+ let begin = payload.timeStampBegin.timeIntervalSince1970 * 1000
312
+ let end = payload.timeStampEnd.timeIntervalSince1970 * 1000
313
+ // A payload that ended before recording was switched on is about a process without consent.
314
+ if end < since { continue }
315
+ let keep = { (report: [String: Any], json: Data, occurrence: String) in
316
+ // The report may have happened anywhere in its payload's window, so only one whose
317
+ // process, by its ID, wrote context at or before the window began is known to have had
318
+ // consent for all of it. The process is the latest with that ID to start before the
319
+ // end; the slack allows only for clocks in telling it from an earlier one.
320
+ guard let pid = report["pid"] as? Int, let entries = consented[pid],
321
+ let start = entries.map({ $0.start }).filter({ $0 <= end + Self.slackMillis }).max(),
322
+ entries.contains(where: { $0.start == start && $0.at <= begin })
323
+ else { return }
324
+ self.write(report, json: json, occurrence: occurrence, in: dir, skipping: acknowledged)
325
+ }
326
+ for (i, crash) in (payload.crashDiagnostics ?? []).enumerated() {
327
+ keep(report(crash: crash, begin: begin, end: end), crash.jsonRepresentation(), "\(begin) \(end) crash \(i)")
328
+ }
329
+ for (i, hang) in (payload.hangDiagnostics ?? []).enumerated() {
330
+ keep(report(hang: hang, begin: begin, end: end), hang.jsonRepresentation(), "\(begin) \(end) hang \(i)")
331
+ }
332
+ }
333
+ prune()
334
+ }
335
+ }
336
+
337
+ /// The ID of a report: the SHA-256 of MetricKit's JSON for it, re-serialised with sorted keys, and
338
+ /// of its occurrence, where it is in its payload. The same report delivered twice has one ID
339
+ /// whatever order the keys came in; two reports alike, as two identical hangs, have two.
340
+ private static func reportID(_ json: Data, occurrence: String) -> String {
341
+ var canonical = json
342
+ if let object = try? JSONSerialization.jsonObject(with: json),
343
+ let sorted = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
344
+ {
345
+ canonical = sorted
346
+ }
347
+ canonical.append(Data("\n\(occurrence)".utf8))
348
+ return SHA256.hash(data: canonical).prefix(16).map { String(format: "%02x", $0) }.joined()
349
+ }
350
+
351
+ private func write(
352
+ _ report: [String: Any], json: Data, occurrence: String, in dir: URL, skipping acknowledged: [String: Double]
353
+ ) {
354
+ let id = Self.reportID(json, occurrence: occurrence)
355
+ let url = dir.appendingPathComponent("\(id).json", isDirectory: false)
356
+ guard acknowledged[id] == nil, !fm.fileExists(atPath: url.path),
357
+ let data = try? JSONSerialization.data(withJSONObject: report)
358
+ else { return }
359
+ try? data.write(to: url, options: .atomic)
360
+ }
361
+
362
+ /// Deletes reports older than maxAge, then the oldest beyond maxReports.
363
+ private func prune() {
364
+ let now = Date()
365
+ var kept: [(URL, Date)] = []
366
+ for url in reportFiles() {
367
+ let modified =
368
+ (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? now
369
+ if now.timeIntervalSince(modified) > Self.maxAge {
370
+ try? fm.removeItem(at: url)
371
+ } else {
372
+ kept.append((url, modified))
373
+ }
374
+ }
375
+ kept.sort { $0.1 > $1.1 }
376
+ for (url, _) in kept.dropFirst(Self.maxReports) {
377
+ try? fm.removeItem(at: url)
378
+ }
379
+ }
380
+
381
+ // MARK: Reports
382
+
383
+ private func base(_ d: MXDiagnostic, kind: String, begin: Double, end: Double, tree: MXCallStackTree)
384
+ -> [String: Any]
385
+ {
386
+ var report: [String: Any] = [
387
+ "kind": kind,
388
+ "begin": begin,
389
+ "end": end,
390
+ "appVersion": d.applicationVersion,
391
+ "appBuild": d.metaData.applicationBuildVersion,
392
+ "osVersion": d.metaData.osVersion,
393
+ ]
394
+ // iOS 17 and later name the process the report is about; reading it from the JSON keeps the
395
+ // module building against every SDK.
396
+ if let meta = (try? JSONSerialization.jsonObject(with: d.metaData.jsonRepresentation())) as? [String: Any],
397
+ let pid = meta["pid"] as? Int
398
+ {
399
+ report["pid"] = pid
400
+ }
401
+ if let stack = (try? JSONSerialization.jsonObject(with: tree.jsonRepresentation())) as? [String: Any] {
402
+ report["callStackTree"] = Self.attributedThreadOnly(stack)
403
+ }
404
+ return report
405
+ }
406
+
407
+ /// The tree with only the thread MetricKit attributes the report to (else the first), the one
408
+ /// stack the JavaScript side reads, so a report holds one thread and not all of them.
409
+ private static func attributedThreadOnly(_ tree: [String: Any]) -> [String: Any] {
410
+ guard let stacks = tree["callStacks"] as? [[String: Any]], !stacks.isEmpty else { return tree }
411
+ let attributed = stacks.first { ($0["threadAttributed"] as? Bool) == true } ?? stacks[0]
412
+ var out = tree
413
+ out["callStacks"] = [attributed]
414
+ return out
415
+ }
416
+
417
+ private func report(crash: MXCrashDiagnostic, begin: Double, end: Double) -> [String: Any] {
418
+ var report = base(crash, kind: "crash", begin: begin, end: end, tree: crash.callStackTree)
419
+ if let v = crash.exceptionType { report["exceptionType"] = v.intValue }
420
+ if let v = crash.exceptionCode { report["exceptionCode"] = v.intValue }
421
+ if let v = crash.signal { report["signal"] = v.intValue }
422
+ if let v = crash.terminationReason { report["terminationReason"] = v }
423
+ if #available(iOS 17.0, *), let reason = crash.exceptionReason {
424
+ report["objcName"] = reason.exceptionName
425
+ report["objcMessage"] = reason.composedMessage
426
+ }
427
+ return report
428
+ }
429
+
430
+ private func report(hang: MXHangDiagnostic, begin: Double, end: Double) -> [String: Any] {
431
+ var report = base(hang, kind: "hang", begin: begin, end: end, tree: hang.callStackTree)
432
+ report["hangSeconds"] = hang.hangDuration.converted(to: .seconds).value
433
+ return report
434
+ }
435
+ }
@@ -0,0 +1,26 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = 'Libo11yNative'
7
+ s.version = package['version']
8
+ s.summary = 'The libo11y native module for React Native on iOS'
9
+ s.description = 'Reads the process start time and keeps the crash and hang reports MetricKit delivers, for @libo11y/rum-react-native.'
10
+ s.license = package['license']
11
+ s.author = 'libo11y'
12
+ s.homepage = 'https://github.com/libo11y/libo11y/tree/main/ts/packages/react-native'
13
+ s.platforms = { :ios => '16.4' }
14
+ s.swift_version = '5.9'
15
+ s.source = { git: 'https://github.com/libo11y/libo11y.git' }
16
+ s.static_framework = true
17
+
18
+ s.dependency 'ExpoModulesCore'
19
+ s.frameworks = 'MetricKit'
20
+
21
+ s.pod_target_xcconfig = {
22
+ 'DEFINES_MODULE' => 'YES'
23
+ }
24
+
25
+ s.source_files = '*.swift'
26
+ end
@@ -0,0 +1,52 @@
1
+ import ExpoModulesCore
2
+
3
+ /// The libo11y native module, ABI 1: the process start time from the kernel, and the crash and hang
4
+ /// reports MetricKit delivers, kept on disk until JavaScript acknowledges them. The JavaScript side is
5
+ /// src/native.ts in @libo11y/react-native, which finds the module through
6
+ /// globalThis.expo.modules.Libo11yNative and works without it.
7
+ ///
8
+ /// setRecording, recordContext and the two reads, contextHistory and pendingDiagnostics, are async
9
+ /// functions, so the JavaScript thread never waits on MetricKit's work or the disk, a revoke can
10
+ /// wait for the deletion and learn when it failed, and a context write says whether it was kept. Strings carry
11
+ /// JSON both ways, so the JavaScript side validates every field.
12
+ public final class Libo11yNativeModule: Module {
13
+ public func definition() -> ModuleDefinition {
14
+ Name("Libo11yNative")
15
+
16
+ OnCreate {
17
+ Libo11yDiagnostics.shared.start()
18
+ }
19
+
20
+ Function("abi") { () -> Int in
21
+ return 1
22
+ }
23
+
24
+ Function("processStart") { () -> Double? in
25
+ return Libo11yProcess.startEpochMillis
26
+ }
27
+
28
+ Function("prewarmed") { () -> Bool in
29
+ return Libo11yProcess.prewarmed
30
+ }
31
+
32
+ AsyncFunction("setRecording") { (on: Bool) in
33
+ try Libo11yDiagnostics.shared.setRecording(on)
34
+ }
35
+
36
+ AsyncFunction("recordContext") { (json: String) -> Bool in
37
+ return Libo11yDiagnostics.shared.recordContext(json)
38
+ }
39
+
40
+ AsyncFunction("contextHistory") { () -> String in
41
+ return Libo11yDiagnostics.shared.contextHistory()
42
+ }
43
+
44
+ AsyncFunction("pendingDiagnostics") { () -> String in
45
+ return Libo11yDiagnostics.shared.pendingDiagnostics()
46
+ }
47
+
48
+ Function("acknowledgeDiagnostics") { (ids: [String]) in
49
+ Libo11yDiagnostics.shared.acknowledge(ids)
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,28 @@
1
+ import Darwin
2
+ import Foundation
3
+
4
+ /// The current process as the kernel reports it.
5
+ enum Libo11yProcess {
6
+ /// When the kernel started this process, in milliseconds since the Unix epoch, from sysctl's
7
+ /// kinfo_proc (p_starttime). It is earlier than anything the app's code can observe, so app_load
8
+ /// starts there unless the process was prewarmed. The context history records it for every
9
+ /// process, prewarmed or not, so a report is never attributed to the process that delivers it.
10
+ /// Nil when sysctl fails.
11
+ static let startEpochMillis: Double? = {
12
+ var info = kinfo_proc()
13
+ var size = MemoryLayout<kinfo_proc>.stride
14
+ var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
15
+ let result = sysctl(&mib, u_int(mib.count), &info, &size, nil, 0)
16
+ guard result == 0, size > 0 else { return nil }
17
+ let start = info.kp_proc.p_un.__p_starttime
18
+ guard start.tv_sec > 0 else { return nil }
19
+ return Double(start.tv_sec) * 1000 + Double(start.tv_usec) / 1000
20
+ }()
21
+
22
+ /// Whether iOS prewarmed this process before the person opened the app, so its start is not
23
+ /// when the app started.
24
+ static let prewarmed: Bool = ProcessInfo.processInfo.environment["ActivePrewarm"] == "1"
25
+
26
+ /// This process's ID.
27
+ static let pid: Int = Int(getpid())
28
+ }