@libo11y/react-native 0.6.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.
package/README.md CHANGED
@@ -54,11 +54,60 @@ and `expo-updates`. They are optional peer dependencies: an app that
54
54
  imports `./expo` installs them, at Expo SDK 58 or later. The main entry
55
55
  imports none of them. Tested on Expo SDK 58 only.
56
56
 
57
+ ## Native module (iOS)
58
+
59
+ The package ships an Expo module, `Libo11yNative`, written in Swift, for
60
+ iOS only. Expo's autolinking adds it to an app that lists
61
+ `@libo11y/react-native` in its own `dependencies`, at the next native
62
+ build (`npx expo prebuild` or EAS Build, then `pod install`). It needs no
63
+ config plugin. It needs iOS 16.4 or later, the minimum of Expo SDK 58's
64
+ modules.
65
+
66
+ - It reads the process start time from the kernel (`sysctl`
67
+ `kinfo_proc`), so `@libo11y/rum-react-native`'s `app_load` starts when
68
+ the process did, unless iOS prewarmed the process. The context history
69
+ records the start of every process, prewarmed or not.
70
+ - It subscribes to MetricKit and keeps each crash and hang report on disk
71
+ while RUM records under consent, at most 32 and none older than 7 days,
72
+ until `@libo11y/rum-react-native`'s `errors()` turns it into a record.
73
+ It keeps a report only when the report names its process (iOS 17 and
74
+ later) and that process wrote context by the time the report's payload
75
+ began, which it does only while RUM records under consent, so consent
76
+ covered the whole time the report may have happened in. It drops any other report, and one from before
77
+ recording was switched on. It remembers handled reports for 8 days, so
78
+ a report delivered again is not kept twice. Two reports alike, such as
79
+ two identical hangs, are kept apart by where they are in MetricKit's
80
+ payloads.
81
+ - A report keeps only the stack of the thread MetricKit attributes it to.
82
+ MetricKit's earlier payloads are read off the module's creating thread,
83
+ and JavaScript reads the reports and the history through async
84
+ functions, at most 512 KiB of reports at a time, so the JavaScript
85
+ thread never waits on the disk.
86
+ - It keeps the last 64 session and screen entries JavaScript writes, with
87
+ the process ID and start time, so a report from an earlier launch maps
88
+ to the session and screen it happened in. Every entry also carries when
89
+ its process first wrote under consent, so that time outlasts the entry
90
+ that set it.
91
+
92
+ Everything lives under the app's `Application Support/libo11y`, which is
93
+ excluded from backups. Revoking consent deletes the reports and the
94
+ history, and the revoke returns once they are gone. A file it cannot
95
+ delete is reported to JavaScript. The cleanup then stays pending on
96
+ disk, or, when even that mark cannot be written, the recording flag is
97
+ invalidated: the module keeps and reads back nothing, and recording
98
+ cannot be switched on again until a retried cleanup deletes everything.
99
+
100
+ The JavaScript looks the module up without importing anything native.
101
+ An app binary built before the module, an Android build, a bare React
102
+ Native app without Expo modules, and tests have no module, and the
103
+ packages then work exactly as before, JavaScript only. That is what an
104
+ over-the-air update running on an older binary gets.
105
+
57
106
  ## Status
58
107
 
59
108
  A preview. The package first ships in `ts/v0.4.0`, is published on npm at
60
- `0.6.0` (and attached as a tarball to the
61
- [`ts/v0.6.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.6.0)),
109
+ `0.7.0` (and attached as a tarball to the
110
+ [`ts/v0.7.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.7.0)),
62
111
  and its API can change in a minor release:
63
112
 
64
113
  ```sh
@@ -12,6 +12,7 @@ export { expoFileStorageWith, type FileLike, type FileSystemLike } from "./expo/
12
12
  export { type ExpoOptions, expoOptionsFrom, withExpoOptions } from "./expo/options.ts";
13
13
  export { installNetworkInstrumentation, type NetworkInstrumentation, type NetworkInstrumentationOptions, RN_SCOPE, } from "./instrumentation/network.ts";
14
14
  export { appStateLifecycle } from "./lifecycle.ts";
15
+ export { type Libo11yNative, libo11yNative, libo11yNativeFrom, NATIVE_ABI, NATIVE_MODULE_NAME, type NativeContextEntry, type NativeDiagnostic, } from "./native.ts";
15
16
  export type { ReactNativeConsentOptions, ReactNativeInstrumentationOptions, ReactNativeSetupOptions, ReactNativeTelemetry, ReactNativeTransportOptions, } from "./options.ts";
16
17
  export { MOBILE_ENV_DEFAULTS, type ReactNativePlatformOptions, reactNativePlatform } from "./platform.ts";
17
18
  export { uuidCrypto } from "./random.ts";
package/dist/internal.js CHANGED
@@ -10,6 +10,7 @@ export { expoFileStorageWith } from "./expo/file-storage.js";
10
10
  export { expoOptionsFrom, withExpoOptions } from "./expo/options.js";
11
11
  export { installNetworkInstrumentation, RN_SCOPE, } from "./instrumentation/network.js";
12
12
  export { appStateLifecycle } from "./lifecycle.js";
13
+ export { libo11yNative, libo11yNativeFrom, NATIVE_ABI, NATIVE_MODULE_NAME, } from "./native.js";
13
14
  export { MOBILE_ENV_DEFAULTS, reactNativePlatform } from "./platform.js";
14
15
  export { uuidCrypto } from "./random.js";
15
16
  export { detectReactNativeResource } from "./resource.js";
@@ -0,0 +1,110 @@
1
+ /** The name the module registers with Expo. */
2
+ export declare const NATIVE_MODULE_NAME = "Libo11yNative";
3
+ /** The interface version of the module this package speaks. */
4
+ export declare const NATIVE_ABI = 1;
5
+ /** One entry of the context history: what was current at `at`, as JavaScript wrote it. */
6
+ export interface NativeContextEntry {
7
+ /** Epoch milliseconds when this became current. */
8
+ readonly at: number;
9
+ readonly sessionId: string;
10
+ readonly viewId: string;
11
+ readonly viewName: string;
12
+ readonly viewKind: string;
13
+ /** The seq the view's next summary would have had. */
14
+ readonly seq: number;
15
+ /** service.version. */
16
+ readonly version?: string;
17
+ /** o11y.rum.app.update_id. */
18
+ readonly updateId?: string;
19
+ /** The writing process's ID, which the module adds. */
20
+ readonly pid?: number;
21
+ /** The writing process's start, epoch milliseconds, which the module adds. */
22
+ readonly processStart?: number;
23
+ /**
24
+ * When the writing process first wrote under consent, epoch milliseconds, which the module adds
25
+ * to every entry, so it outlasts the entry that set it.
26
+ */
27
+ readonly since?: number;
28
+ /** Written as a fatal JavaScript error ends the process, so its native crash is not reported again. */
29
+ readonly fatal?: boolean;
30
+ /** Whether the session was kept (sampled or retained) when this was written. */
31
+ readonly kept?: boolean;
32
+ /**
33
+ * Written when a later launch sent a late summary of the view: seq is the view's next seq then.
34
+ * It names no context of its own, and attribution skips it.
35
+ */
36
+ readonly late?: boolean;
37
+ /** On a late entry, the report it counted, so a report tried again is not counted twice. */
38
+ readonly report?: string;
39
+ }
40
+ /** A crash or hang report MetricKit delivered, as the module keeps it. */
41
+ export interface NativeDiagnostic {
42
+ /** Stable for one report, for acknowledgeDiagnostics. */
43
+ readonly id: string;
44
+ readonly kind: "crash" | "hang";
45
+ /** The delivering payload's time range, epoch milliseconds. */
46
+ readonly begin: number;
47
+ readonly end: number;
48
+ /** The process the report is about, when the operating system says (iOS 17 and later). */
49
+ readonly pid?: number;
50
+ readonly appVersion?: string;
51
+ readonly appBuild?: string;
52
+ readonly osVersion?: string;
53
+ /** The Mach exception type, such as 1 for EXC_BAD_ACCESS. */
54
+ readonly exceptionType?: number;
55
+ readonly exceptionCode?: number;
56
+ /** The POSIX signal number, such as 11 for SIGSEGV. */
57
+ readonly signal?: number;
58
+ readonly terminationReason?: string;
59
+ /** The Objective-C or Swift exception's name and message (iOS 17 and later). */
60
+ readonly objcName?: string;
61
+ readonly objcMessage?: string;
62
+ /** How long a hang lasted, in seconds. */
63
+ readonly hangSeconds?: number;
64
+ /** MetricKit's MXCallStackTree JSON. */
65
+ readonly callStackTree?: unknown;
66
+ }
67
+ /** The guarded bridge to the module. */
68
+ export interface Libo11yNative {
69
+ /**
70
+ * The process start time from the kernel (sysctl kinfo_proc), epoch milliseconds, also for a
71
+ * prewarmed process: the context history and attribution need it.
72
+ */
73
+ processStart(): number | undefined;
74
+ /**
75
+ * Whether iOS prewarmed this process before the person opened the app, so its process start is
76
+ * not when the app started.
77
+ */
78
+ prewarmed(): boolean;
79
+ /**
80
+ * Whether the module keeps MetricKit reports: on while RUM records under consent. Off also
81
+ * deletes the reports and the context history it holds. Resolves once the module did, off the
82
+ * JavaScript thread. Rejects when it could not: off then still stops the module recording in
83
+ * this process, and a later off (a denied start, a revoke) deletes again.
84
+ */
85
+ setRecording(on: boolean): Promise<void>;
86
+ /**
87
+ * Appends one context entry; the module adds the process ID and start and keeps the last 64.
88
+ * Resolves true once it kept it, false when it did not, as while recording is off.
89
+ */
90
+ recordContext(entry: NativeContextEntry): Promise<boolean>;
91
+ /** The context history. The module reads it off the JavaScript thread. */
92
+ contextHistory(): Promise<NativeContextEntry[]>;
93
+ /**
94
+ * The reports the module keeps, oldest first, as many as fit its batch bound; the rest come in
95
+ * a later call. The module reads them off the JavaScript thread.
96
+ */
97
+ pendingDiagnostics(): Promise<NativeDiagnostic[]>;
98
+ /** Deletes the reports with these IDs. */
99
+ acknowledgeDiagnostics(ids: readonly string[]): void;
100
+ }
101
+ /**
102
+ * The bridge over raw, the module object Expo installed, or undefined when raw is not the module
103
+ * this package speaks: missing, a function missing, or another ABI version.
104
+ */
105
+ export declare function libo11yNativeFrom(raw: unknown): Libo11yNative | undefined;
106
+ /**
107
+ * The module of this app binary, or undefined without one: an OTA update running on a binary built
108
+ * before the module, Android, or a runtime without Expo modules.
109
+ */
110
+ export declare function libo11yNative(): Libo11yNative | undefined;
package/dist/native.js ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The optional libo11y native module (Libo11yNative), an Expo module for iOS that ships inside this
3
+ * package: it reads the process start time and keeps the crash and hang reports MetricKit delivers
4
+ * (ios/). An app binary built before the module was added, an Android build, a bare React Native
5
+ * app without Expo modules, and node tests have no module, so everything here works without it:
6
+ * libo11yNative() is then undefined and the JavaScript side runs alone.
7
+ *
8
+ * The lookup reads globalThis.expo.modules, the object Expo's requireOptionalNativeModule returns,
9
+ * so this file imports neither expo-modules-core nor react-native. A module of another ABI version
10
+ * is ignored. Every call but setRecording is guarded: a native failure becomes undefined, false
11
+ * or an empty list, never a throw into the app. setRecording rejects, so a failed cleanup is known. The two reads and setRecording are async functions, so the module reads and
12
+ * deletes its files off the JavaScript thread, and a caller can wait for the deletion.
13
+ */
14
+ import { diag } from "@opentelemetry/api";
15
+ /** The name the module registers with Expo. */
16
+ export const NATIVE_MODULE_NAME = "Libo11yNative";
17
+ /** The interface version of the module this package speaks. */
18
+ export const NATIVE_ABI = 1;
19
+ const FUNCTIONS = [
20
+ "abi",
21
+ "processStart",
22
+ "prewarmed",
23
+ "setRecording",
24
+ "recordContext",
25
+ "contextHistory",
26
+ "pendingDiagnostics",
27
+ "acknowledgeDiagnostics",
28
+ ];
29
+ let warned = false;
30
+ function warnOnce(what, err) {
31
+ if (warned)
32
+ return;
33
+ warned = true;
34
+ diag.warn(`o11y: the libo11y native module failed in ${what}`, err);
35
+ }
36
+ function guard(what, fallback, call) {
37
+ try {
38
+ return call();
39
+ }
40
+ catch (err) {
41
+ warnOnce(what, err);
42
+ return fallback;
43
+ }
44
+ }
45
+ async function guardAsync(what, fallback, call) {
46
+ try {
47
+ return await call();
48
+ }
49
+ catch (err) {
50
+ warnOnce(what, err);
51
+ return fallback;
52
+ }
53
+ }
54
+ const isObject = (v) => typeof v === "object" && v !== null;
55
+ const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
56
+ const isString = (v) => typeof v === "string";
57
+ function parseList(raw) {
58
+ if (typeof raw !== "string")
59
+ return [];
60
+ try {
61
+ const v = JSON.parse(raw);
62
+ return Array.isArray(v) ? v : [];
63
+ }
64
+ catch {
65
+ return [];
66
+ }
67
+ }
68
+ /** Copies the optional fields of src that pass check. */
69
+ function optional(src, keys, check) {
70
+ const out = {};
71
+ for (const k of keys)
72
+ if (check(src[k]))
73
+ out[k] = src[k];
74
+ return out;
75
+ }
76
+ function contextEntry(v) {
77
+ if (!isObject(v))
78
+ return undefined;
79
+ const { at, sessionId, viewId, viewName, viewKind, seq } = v;
80
+ if (!isFiniteNumber(at) || !isString(sessionId) || !isString(viewId) || !isString(viewName))
81
+ return undefined;
82
+ if (!isString(viewKind) || !isFiniteNumber(seq))
83
+ return undefined;
84
+ return {
85
+ at,
86
+ sessionId,
87
+ viewId,
88
+ viewName,
89
+ viewKind,
90
+ seq,
91
+ ...optional(v, ["version", "updateId"], isString),
92
+ ...optional(v, ["pid", "processStart", "since"], isFiniteNumber),
93
+ ...(v.fatal === true ? { fatal: true } : {}),
94
+ ...(typeof v.kept === "boolean" ? { kept: v.kept } : {}),
95
+ ...(v.late === true ? { late: true } : {}),
96
+ ...(isString(v.report) ? { report: v.report } : {}),
97
+ };
98
+ }
99
+ function diagnostic(v) {
100
+ if (!isObject(v))
101
+ return undefined;
102
+ const { id, kind, begin, end } = v;
103
+ if (!isString(id) || id === "" || (kind !== "crash" && kind !== "hang"))
104
+ return undefined;
105
+ if (!isFiniteNumber(begin) || !isFiniteNumber(end))
106
+ return undefined;
107
+ return {
108
+ id,
109
+ kind,
110
+ begin,
111
+ end,
112
+ ...optional(v, ["pid", "exceptionType", "exceptionCode", "signal", "hangSeconds"], isFiniteNumber),
113
+ ...optional(v, ["appVersion", "appBuild", "osVersion", "terminationReason", "objcName", "objcMessage"], isString),
114
+ ...(isObject(v.callStackTree) ? { callStackTree: v.callStackTree } : {}),
115
+ };
116
+ }
117
+ function bridge(m) {
118
+ return {
119
+ processStart() {
120
+ return guard("processStart", undefined, () => {
121
+ const v = m.processStart();
122
+ return isFiniteNumber(v) && v > 0 ? v : undefined;
123
+ });
124
+ },
125
+ prewarmed() {
126
+ return guard("prewarmed", false, () => m.prewarmed() === true);
127
+ },
128
+ async setRecording(on) {
129
+ // Not guarded: a cleanup the module could not do is the caller's to know.
130
+ await m.setRecording(on);
131
+ },
132
+ recordContext(entry) {
133
+ return guardAsync("recordContext", false, async () => (await m.recordContext(JSON.stringify(entry))) === true);
134
+ },
135
+ contextHistory() {
136
+ return guardAsync("contextHistory", [], async () => parseList(await m.contextHistory()).flatMap((e) => contextEntry(e) ?? []));
137
+ },
138
+ pendingDiagnostics() {
139
+ return guardAsync("pendingDiagnostics", [], async () => parseList(await m.pendingDiagnostics()).flatMap((d) => diagnostic(d) ?? []));
140
+ },
141
+ acknowledgeDiagnostics(ids) {
142
+ if (ids.length === 0)
143
+ return;
144
+ guard("acknowledgeDiagnostics", undefined, () => m.acknowledgeDiagnostics([...ids]));
145
+ },
146
+ };
147
+ }
148
+ /**
149
+ * The bridge over raw, the module object Expo installed, or undefined when raw is not the module
150
+ * this package speaks: missing, a function missing, or another ABI version.
151
+ */
152
+ export function libo11yNativeFrom(raw) {
153
+ if (!isObject(raw) && typeof raw !== "function")
154
+ return undefined;
155
+ const m = raw;
156
+ if (FUNCTIONS.some((f) => typeof m[f] !== "function"))
157
+ return undefined;
158
+ const module = raw;
159
+ const abi = guard("abi", undefined, () => module.abi());
160
+ return abi === NATIVE_ABI ? bridge(module) : undefined;
161
+ }
162
+ /**
163
+ * The module of this app binary, or undefined without one: an OTA update running on a binary built
164
+ * before the module, Android, or a runtime without Expo modules.
165
+ */
166
+ export function libo11yNative() {
167
+ const modules = globalThis.expo?.modules;
168
+ return libo11yNativeFrom(guard("lookup", undefined, () => modules?.[NATIVE_MODULE_NAME]));
169
+ }
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.6.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.6.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
+ }
package/package.json CHANGED
@@ -1,10 +1,18 @@
1
1
  {
2
2
  "name": "@libo11y/react-native",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "The libo11y React Native platform for TypeScript: setup over the OpenTelemetry JS 3.x providers on Hermes, the mobile resource, an OTLP/HTTP transport with a persistent retry queue on device storage, AppState flushing, the consent gate, and fetch and XHR spans.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
+ "files": [
9
+ "dist",
10
+ "ios/*.swift",
11
+ "ios/*.podspec",
12
+ "expo-module.config.json",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
8
16
  "exports": {
9
17
  ".": {
10
18
  "types": "./dist/index.d.ts",
@@ -29,9 +37,9 @@
29
37
  "directory": "ts/packages/react-native"
30
38
  },
31
39
  "dependencies": {
32
- "@libo11y/core": "0.6.0",
33
- "@libo11y/spec": "0.6.0",
34
- "@libo11y/web": "0.6.0",
40
+ "@libo11y/core": "0.7.0",
41
+ "@libo11y/spec": "0.7.0",
42
+ "@libo11y/web": "0.7.0",
35
43
  "@opentelemetry/core": "3.1.1"
36
44
  },
37
45
  "peerDependencies": {
@@ -57,18 +65,13 @@
57
65
  }
58
66
  },
59
67
  "devDependencies": {
60
- "@libo11y/test": "0.6.0",
68
+ "@libo11y/test": "0.7.0",
61
69
  "@opentelemetry/api": "1.10.0",
62
70
  "@opentelemetry/sdk-trace": "3.1.1",
63
71
  "@types/react": "19.3.0",
64
72
  "react": "19.3.1",
65
73
  "react-native": "0.88.1"
66
74
  },
67
- "files": [
68
- "dist",
69
- "README.md",
70
- "LICENSE"
71
- ],
72
75
  "publishConfig": {
73
76
  "access": "public",
74
77
  "provenance": true