@libo11y/rum-react-native 0.6.0 → 0.8.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
@@ -98,9 +98,13 @@ effect of the root component. It ends the first screen's span and the
98
98
  screen's is a root linked to the action that caused it. Going to the
99
99
  background (AppState `background`, or `inactive` on iOS) emits the
100
100
  screen's `o11y.rum.view.summary` and flushes.
101
- - **App start.** One `app_load` span per process, from
102
- `performance.rnStartupTiming.startTime` (or, without it, when this
103
- package was loaded) to the first screen's render, at most 60 seconds.
101
+ - **App start.** One `app_load` span per process, from the process start
102
+ to the first screen's render, at most 60 seconds. With the libo11y
103
+ native module (see [Native crashes and hangs](#native-crashes-and-hangs))
104
+ the start is the kernel's process start time, unless iOS prewarmed the
105
+ process before the person opened the app. Without it, the start is
106
+ `performance.rnStartupTiming.startTime`, or when this package was
107
+ loaded.
104
108
  When consent is granted after the first screen rendered, even after
105
109
  other screens, the span is still recorded, with the times remembered
106
110
  from before the grant. An app that leaves its first screen before it
@@ -109,7 +113,9 @@ effect of the root component. It ends the first screen's span and the
109
113
  toward the screen's summary and leave breadcrumbs.
110
114
  `rum.onRequestStart` hooks run on each of them, which is how
111
115
  `connectRequestNaming` names Connect calls.
112
- - **Errors**, with `errors()`. See [Errors](#errors).
116
+ - **Errors**, with `errors()`. See [Errors](#errors). On iOS with the
117
+ native module, also native crashes and hangs. See
118
+ [Native crashes and hangs](#native-crashes-and-hangs).
113
119
  - **Taps and frustration signals**, with `taps()` and `RumTouchBoundary`.
114
120
  See [Taps](#taps).
115
121
 
@@ -203,6 +209,112 @@ has no update ID: upload its composed map with `--release` and no
203
209
 
204
210
  Development stacks point at Metro and are sent as they are.
205
211
 
212
+ ## Native crashes and hangs
213
+
214
+ On iOS, `@libo11y/react-native` ships an Expo module, `Libo11yNative`.
215
+ With it in the app binary, `errors()` also records the crashes and hangs
216
+ that MetricKit reports. MetricKit reports a crash on the app's next
217
+ launch, not when it happens, and a hang on the next launch or while the
218
+ app still runs. It runs outside the app, so it cannot crash the app or
219
+ slow it down. MetricKit names the process a report is about from iOS 17,
220
+ and only such reports are recorded.
221
+
222
+ - A **crash** is `o11y.rum.error` with source `crash`. `exception.type` is
223
+ the Objective-C or Swift exception name when iOS reports one (iOS 17
224
+ and later), else the Mach exception (`EXC_BAD_ACCESS`), else the
225
+ signal. `o11y.rum.error.signal` is the signal, such as `SIGSEGV`.
226
+ - A **hang** is source `hang`, type `AppHang`, with
227
+ `o11y.rum.error.hang_duration` in seconds.
228
+ - `exception.stacktrace` holds the crashed thread's stack, or for a hang
229
+ the main thread's most sampled stack, innermost frame first, one frame
230
+ per line as
231
+ `<index> <binary> 0x<address> 0x<load address> + <offset>`.
232
+ `o11y.rum.error.binary_images` lists the UUID, load address and name of
233
+ each binary in it. The gateway resolves the frames of every binary
234
+ whose dSYM was uploaded with `libo11y-sourcemaps dsyms`, and leaves
235
+ system frameworks as they are.
236
+
237
+ Each record keeps the session, screen, update ID and time of the moment
238
+ it happened, and nothing of the launch that delivers it, such as the
239
+ current user ID. While RUM runs, every change of session, screen, screen
240
+ name or whether the session is kept, and every move to the background,
241
+ writes them to a small history file through the module, which adds the
242
+ process ID and start time. MetricKit gives a report only the time range
243
+ of the payload it came in, so the report may have happened anywhere in
244
+ it. A report maps to the last entry its own process wrote at or before
245
+ the range's end, and is kept only when that process wrote an entry at or
246
+ before the range's start, so consent covered the whole range. Any other
247
+ report, and one without a process ID, is dropped, because nothing shows
248
+ its process recorded under consent when it happened. The cost: reports
249
+ from the launch that first granted consent, and any whose range starts
250
+ before its launch wrote its first entry, are dropped. A fatal JavaScript error marks its entry, so the native crash
251
+ React Native raises for it (`RCTFatal`) is not reported a second time.
252
+ The error also counts in a view summary of that screen, so the gateway's
253
+ error metrics include it for every consented session: in the screen's
254
+ own summary for a hang of the running app on its current screen, else in
255
+ one more summary of that screen, whose index the history keeps so a
256
+ later launch continues it. The record carries the `service.version` of
257
+ the launch that crashed, from its context entry or else from MetricKit,
258
+ so a crash of an earlier app version reported after an update is counted
259
+ under that version.
260
+
261
+ Consent applies as for JavaScript errors. The module keeps reports only
262
+ while RUM records under consent, and drops a report whose time is before
263
+ recording was switched on, so a report is about a process that could
264
+ have had consent. Revoking consent, or a launch that starts denied,
265
+ deletes the reports and the history it holds. Reports already handled are
266
+ remembered for 8 days, so MetricKit delivering one again does not send it
267
+ twice.
268
+ A report of an earlier session keeps the decision that session had: it
269
+ is sent when the session was kept, and when sampling left it out it is
270
+ not sent but still counted in the summary. A report is acknowledged, and
271
+ deleted from the module, once the pipeline took its record and its
272
+ summary, a flush exported them to delivery or its retry queue, and the
273
+ module wrote the mark that it was counted, so a crash before then does
274
+ not lose it. A report whose record or summary the pipeline dropped, as a
275
+ failing `attrReplacer` does, or whose mark could not be written, stays
276
+ for the next read. One read again after a failed flush sends
277
+ its record and its summary again; one read again after it was marked
278
+ counted sends its record but no summary.
279
+
280
+ Delivery is known per batch, not per record. A flush that fails for any
281
+ batch of logs leaves every report of that read for the next one, so a
282
+ report whose own batch did get through is sent, and counted, twice, and
283
+ a record the batch processor drops when its queue is full is not seen.
284
+
285
+ Revoking consent, or a launch that starts denied, returns once the
286
+ module has deleted what it holds. When it cannot delete a file, the
287
+ failure is logged, and nothing is recorded or read until a later
288
+ cleanup succeeds: the next revoke or denied start, or the next grant,
289
+ which retries it first. A fatal JavaScript error waits, within its
290
+ deadline, for the flush and for its context to be marked fatal. The module reads
291
+ its reports when `errors()` starts, 15 and 60 seconds later, then every
292
+ minute while RUM records, because MetricKit delivers a moment after
293
+ launch and sometimes later.
294
+
295
+ ### Adopting the module in an Expo app
296
+
297
+ The module needs a new native build. Over-the-air updates keep working
298
+ on a binary built without it: the JavaScript finds no module and runs as
299
+ before.
300
+
301
+ 1. Add `@libo11y/react-native` to the app's own `dependencies`, at the
302
+ same version as `@libo11y/rum-react-native`, so Expo's autolinking
303
+ finds it. No config plugin and no `app.json` change is needed, because
304
+ MetricKit needs no entitlement and no `Info.plist` key.
305
+ 2. Build as usual. `npx expo prebuild` (or EAS Build) and `pod install`
306
+ add the `Libo11yNative` pod. It needs iOS 16.4 or later, the minimum
307
+ of Expo SDK 58's modules. Android builds include nothing from it.
308
+ 3. Keep `errors()` in `rum.collectors`.
309
+ 4. Upload each build's dSYMs, so native frames resolve. See
310
+ [`@libo11y/sourcemaps`](../sourcemaps#dsyms). Hermes is a prebuilt
311
+ framework without a dSYM in the archive. Download its dSYM from the
312
+ React Native release and upload it too.
313
+
314
+ The iOS simulator delivers no MetricKit reports. Check native crashes on
315
+ a device: crash the app, open it again, and the crash arrives with the
316
+ first batch.
317
+
206
318
  ## Taps
207
319
 
208
320
  `taps()` records the touches `RumTouchBoundary` passes it. A touch is a
@@ -279,10 +391,10 @@ every `onPress`, which would put RUM inside every press of the app.
279
391
 
280
392
  ## Status
281
393
 
282
- A preview. The package first ships in `ts/v0.6.0`, is published on npm at
283
- `0.6.0` (and attached as a tarball to the
284
- [`ts/v0.6.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.6.0)),
394
+ A preview. The package first ships in `ts/v0.6.0`, is published on npm at `0.8.0` (and attached as a tarball to the
395
+ [`ts/v0.8.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.8.0)),
285
396
  and its API can change in a minor release. Errors, taps and the Expo
286
397
  Router adapter [`@libo11y/rum-expo-router`](../rum-expo-router) ship with
287
- it. Native crashes, hangs and the native app start come with the native
288
- module.
398
+ it. Native crashes and hangs on iOS and the native app start come with
399
+ the native module in `@libo11y/react-native`, from `ts/v0.7.0`. Android
400
+ native crashes are not recorded yet.
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * The app_load span on React Native: once per process, the app's start until its
3
- * first screen rendered. It starts at performance.rnStartupTiming.startTime when that is a finite
4
- * time before setup (React Native's measure of the native process start), else when
5
- * `@libo11y/rum-react-native` was first evaluated. The setup reports every rum.startView and
3
+ * first screen rendered. It starts at the process start the libo11y native module reads from the
4
+ * kernel (sysctl kinfo_proc) when the app binary has the module, else at
5
+ * performance.rnStartupTiming.startTime when that is a finite time before setup (React Native's
6
+ * measure of the native process start), else when `@libo11y/rum-react-native` was first evaluated. The setup reports every rum.startView and
6
7
  * rum.viewRendered here, consent or not, so the first screen's render is known even when consent
7
8
  * comes later or after other screens. app_load is recorded when the first grant of the process
8
9
  * begins the load view, with its session.id and view ID, and is the load view span's parent
@@ -30,6 +31,8 @@ export interface AppStartOptions {
30
31
  readonly env: RumReactNativeEnv;
31
32
  /** performance.now(). */
32
33
  readonly now: () => number;
34
+ /** The epoch milliseconds performance.now() counts from, to place env.processStart. Default 0. */
35
+ readonly timeOrigin?: number;
33
36
  /** Default APP_LOAD_CAP_MILLIS. */
34
37
  readonly capMillis?: number;
35
38
  }
package/dist/app-start.js CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * The app_load span on React Native: once per process, the app's start until its
3
- * first screen rendered. It starts at performance.rnStartupTiming.startTime when that is a finite
4
- * time before setup (React Native's measure of the native process start), else when
5
- * `@libo11y/rum-react-native` was first evaluated. The setup reports every rum.startView and
3
+ * first screen rendered. It starts at the process start the libo11y native module reads from the
4
+ * kernel (sysctl kinfo_proc) when the app binary has the module, else at
5
+ * performance.rnStartupTiming.startTime when that is a finite time before setup (React Native's
6
+ * measure of the native process start), else when `@libo11y/rum-react-native` was first evaluated. The setup reports every rum.startView and
6
7
  * rum.viewRendered here, consent or not, so the first screen's render is known even when consent
7
8
  * comes later or after other screens. app_load is recorded when the first grant of the process
8
9
  * begins the load view, with its session.id and view ID, and is the load view span's parent
@@ -14,14 +15,25 @@ import { ATTR_RUM_PLATFORM, ATTR_RUM_SPAN_SHAPE, ATTR_RUM_VIEW_ID, RUM_SPAN_SHAP
14
15
  import { ROOT_CONTEXT, SpanKind } from "@opentelemetry/api";
15
16
  /** app_load ends this long after it started at the latest. */
16
17
  export const APP_LOAD_CAP_MILLIS = 60_000;
17
- /** The app start, in performance.now() time: React Native's process start when it is usable. */
18
- function startOf(env, now) {
18
+ /** A start in performance.now() time that is usable: finite, not negative, and before now. */
19
+ const usable = (s, now) => typeof s === "number" && Number.isFinite(s) && s >= 0 && s < now;
20
+ /**
21
+ * The app start, in performance.now() time: the process start the native module read from the
22
+ * kernel, else React Native's measure of it, else when this package loaded.
23
+ */
24
+ function startOf(env, now, timeOrigin, capMillis) {
25
+ const native = env.processStart === undefined ? undefined : env.processStart - timeOrigin;
26
+ // A process iOS prewarmed started long before the person opened the app: such a start is not
27
+ // the app's, so it is ignored when it is more than the cap before the JavaScript loaded.
28
+ if (usable(native, now) && env.loadedAt - native <= capMillis)
29
+ return native;
19
30
  const s = env.startupTiming?.startTime;
20
- return typeof s === "number" && Number.isFinite(s) && s >= 0 && s < now ? s : env.loadedAt;
31
+ return usable(s, now) ? s : env.loadedAt;
21
32
  }
22
33
  export function createAppStart(o) {
23
- const start = startOf(o.env, o.now());
24
- const capAt = start + (o.capMillis ?? APP_LOAD_CAP_MILLIS);
34
+ const cap = o.capMillis ?? APP_LOAD_CAP_MILLIS;
35
+ const start = startOf(o.env, o.now(), o.timeOrigin ?? 0, cap);
36
+ const capAt = start + cap;
25
37
  let recorded = false;
26
38
  /** The first screen was left before it rendered. */
27
39
  let left = false;
@@ -2,6 +2,7 @@
2
2
  * Contract. What the React Native RUM collectors read from the runtime. Internal: env.ts reads the
3
3
  * real globals, and tests pass a fake, so no module a test imports loads react-native.
4
4
  */
5
+ import type { Libo11yNative } from "@libo11y/react-native/internal";
5
6
  /** React Native's performance.rnStartupTiming, in performance.now() time. */
6
7
  export interface StartupTimingLike {
7
8
  /** When the native process started, as React Native measures it. */
@@ -12,6 +13,11 @@ export interface StartupTimingLike {
12
13
  export interface RumReactNativeEnv {
13
14
  /** performance.rnStartupTiming, where the runtime has it. */
14
15
  readonly startupTiming?: StartupTimingLike;
16
+ /**
17
+ * The process start time the libo11y native module reads from the kernel, epoch milliseconds.
18
+ * Absent without the module.
19
+ */
20
+ readonly processStart?: number;
15
21
  /** performance.now() when `@libo11y/rum-react-native` was first evaluated: the app start fallback. */
16
22
  readonly loadedAt: number;
17
23
  /** False while the app is in the background, or inactive on iOS. */
@@ -45,6 +51,11 @@ export interface HermesInternalLike {
45
51
  }
46
52
  /** What the errors collector reads from the runtime. */
47
53
  export interface ErrorsEnv {
54
+ /**
55
+ * The libo11y native module, for native crashes and hangs. Absent without it, as on Android or
56
+ * on an app binary built before the module, and the collector then records JavaScript errors only.
57
+ */
58
+ readonly native?: Libo11yNative;
48
59
  /** The ErrorUtils global, absent outside React Native. */
49
60
  readonly errorUtils?: ErrorUtilsLike;
50
61
  /** The HermesInternal global, absent on another engine. */
@@ -1,5 +1 @@
1
- /**
2
- * Contract. What the React Native RUM collectors read from the runtime. Internal: env.ts reads the
3
- * real globals, and tests pass a fake, so no module a test imports loads react-native.
4
- */
5
1
  export {};
package/dist/env.d.ts CHANGED
@@ -6,7 +6,10 @@ import type { RumReactNativeDeps } from "./setup.ts";
6
6
  export declare function defaultRumEnv(lifecycle?: AppLifecycle): RumReactNativeEnv;
7
7
  /** The runtime's timers. */
8
8
  export declare const runtimeTimers: SettleTimers;
9
- /** React Native's ErrorUtils and Hermes' HermesInternal globals, the platform and __DEV__, for errors(). */
9
+ /**
10
+ * React Native's ErrorUtils and Hermes' HermesInternal globals, the platform and __DEV__, and the
11
+ * libo11y native module when the app binary has it, for errors().
12
+ */
10
13
  export declare function defaultErrorsEnv(): ErrorsEnv;
11
14
  /** The real dependencies of setupRumReactNativeWith. */
12
15
  export declare function defaultRumReactNativeDeps(): RumReactNativeDeps;
package/dist/env.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * react-native, so node tests never load it (boundary.test.ts enforces that).
5
5
  */
6
6
  import { defaultReactNativeDeps, defaultReactNativeEnv } from "@libo11y/react-native/env";
7
- import { appStateLifecycle } from "@libo11y/react-native/internal";
7
+ import { appStateLifecycle, libo11yNative } from "@libo11y/react-native/internal";
8
8
  const perf = globalThis
9
9
  .performance;
10
10
  /** performance.now() when this module was first evaluated: the app start without rnStartupTiming. */
@@ -12,8 +12,12 @@ const LOADED_AT = perf?.now() ?? 0;
12
12
  /** React Native's frames, timers and startup timing, with the app's lifecycle for visible. */
13
13
  export function defaultRumEnv(lifecycle = appStateLifecycle(defaultReactNativeEnv().appState)) {
14
14
  const startup = perf?.rnStartupTiming;
15
+ // A prewarmed process started before the person opened the app: app_load does not start there.
16
+ const native = libo11yNative();
17
+ const processStart = native === undefined || native.prewarmed() ? undefined : native.processStart();
15
18
  return {
16
19
  ...(startup === undefined ? {} : { startupTiming: startup }),
20
+ ...(processStart === undefined ? {} : { processStart }),
17
21
  loadedAt: LOADED_AT,
18
22
  visible: () => lifecycle.visible(),
19
23
  requestAnimationFrame: (cb) => requestAnimationFrame(cb),
@@ -26,11 +30,16 @@ export const runtimeTimers = {
26
30
  setTimeout: (cb, ms) => setTimeout(cb, ms),
27
31
  clearTimeout: (h) => clearTimeout(h),
28
32
  };
29
- /** React Native's ErrorUtils and Hermes' HermesInternal globals, the platform and __DEV__, for errors(). */
33
+ /**
34
+ * React Native's ErrorUtils and Hermes' HermesInternal globals, the platform and __DEV__, and the
35
+ * libo11y native module when the app binary has it, for errors().
36
+ */
30
37
  export function defaultErrorsEnv() {
31
38
  const g = globalThis;
32
39
  const rn = defaultReactNativeEnv();
40
+ const native = libo11yNative();
33
41
  return {
42
+ ...(native === undefined ? {} : { native }),
34
43
  ...(g.ErrorUtils == null ? {} : { errorUtils: g.ErrorUtils }),
35
44
  ...(g.HermesInternal == null ? {} : { hermes: g.HermesInternal }),
36
45
  os: rn.os,
package/dist/errors.d.ts CHANGED
@@ -32,6 +32,11 @@
32
32
  * phone. Engine frames (native, InternalBytecode.js) are kept. Development stacks point at Metro
33
33
  * and are kept as they are.
34
34
  *
35
+ * Native crashes and hangs (iOS). With the libo11y native module (env.native), MetricKit's crash and
36
+ * hang reports become o11y.rum.error records with source crash or hang, attributed to the session
37
+ * and screen they happened in (native-reports.ts). Without the module, as on Android or on an app
38
+ * binary built before it, the collector records JavaScript errors only.
39
+ *
35
40
  * Every error goes through recordError, so it counts in the screen's summary, retains an unsampled
36
41
  * session, and carries the breadcrumbs. An error raised while one is being recorded is not recorded
37
42
  * again. Stop restores the previous global handler while RUM's is still the installed one; a
@@ -45,6 +50,8 @@ export declare const FATAL_FLUSH_MILLIS = 2000;
45
50
  export interface ErrorsWithOptions {
46
51
  /** Default FATAL_FLUSH_MILLIS. */
47
52
  readonly fatalFlushMillis?: number;
53
+ /** When native reports are read after the start, then every last of these. Default POLL_MILLIS of native-reports.ts. */
54
+ readonly nativePollMillis?: readonly number[];
48
55
  }
49
56
  /** The errors collector over env. */
50
57
  export declare function errorsWith(env: ErrorsEnv, o?: ErrorsWithOptions): RumCollector;
package/dist/errors.js CHANGED
@@ -32,6 +32,11 @@
32
32
  * phone. Engine frames (native, InternalBytecode.js) are kept. Development stacks point at Metro
33
33
  * and are kept as they are.
34
34
  *
35
+ * Native crashes and hangs (iOS). With the libo11y native module (env.native), MetricKit's crash and
36
+ * hang reports become o11y.rum.error records with source crash or hang, attributed to the session
37
+ * and screen they happened in (native-reports.ts). Without the module, as on Android or on an app
38
+ * binary built before it, the collector records JavaScript errors only.
39
+ *
35
40
  * Every error goes through recordError, so it counts in the screen's summary, retains an unsampled
36
41
  * session, and carries the breadcrumbs. An error raised while one is being recorded is not recorded
37
42
  * again. Stop restores the previous global handler while RUM's is still the installed one; a
@@ -40,6 +45,7 @@
40
45
  import { normalizeError, recordError } from "@libo11y/rum/core";
41
46
  import { diag } from "@opentelemetry/api";
42
47
  import { hermesStack } from "./hermes-stack.js";
48
+ import { startNativeReports } from "./native-reports.js";
43
49
  /** How long a fatal error in a release build waits for the flush before it reaches the previous handler. */
44
50
  export const FATAL_FLUSH_MILLIS = 2000;
45
51
  /** The error.type values of a request the app aborted, which is not a failure. */
@@ -87,6 +93,24 @@ export function errorsWith(env, o = {}) {
87
93
  const flushMillis = o.fatalFlushMillis ?? FATAL_FLUSH_MILLIS;
88
94
  return {
89
95
  name: "errors",
96
+ // RUM erases its storage on a denied start and on every revoke, also when this collector is not
97
+ // running (remote configuration switched it off): the native module then stops keeping reports
98
+ // and deletes what it holds, and the erase waits until it has.
99
+ ...(env.native === undefined
100
+ ? {}
101
+ : {
102
+ clear: async () => {
103
+ try {
104
+ await env.native?.setRecording(false);
105
+ }
106
+ catch (err) {
107
+ // The module stops recording in this process anyway; the next denied start or
108
+ // revoke deletes again.
109
+ diag.warn("o11y: rum: the native module could not delete what it holds", err);
110
+ throw err;
111
+ }
112
+ },
113
+ }),
90
114
  start(rt) {
91
115
  let stopped = false;
92
116
  let recording = false;
@@ -167,7 +191,8 @@ export function errorsWith(env, o = {}) {
167
191
  catch (err) {
168
192
  diag.warn("o11y: rum: emitting the summary before a crash failed", err);
169
193
  }
170
- rt.telemetry.forceFlush().then(go, go);
194
+ // The crash waits for the flush and for the fatal context, within the deadline.
195
+ Promise.all([nativeReports?.fatal(), rt.telemetry.forceFlush()]).then(go, go);
171
196
  };
172
197
  if (utils !== undefined && previous !== undefined)
173
198
  utils.setGlobalHandler(handler);
@@ -200,8 +225,17 @@ export function errorsWith(env, o = {}) {
200
225
  }
201
226
  }
202
227
  });
228
+ const nativeReports = env.native === undefined
229
+ ? undefined
230
+ : startNativeReports(rt, {
231
+ native: env.native,
232
+ setTimeout: env.setTimeout,
233
+ clearTimeout: env.clearTimeout,
234
+ ...(o.nativePollMillis === undefined ? {} : { pollMillis: o.nativePollMillis }),
235
+ });
203
236
  return () => {
204
237
  stopped = true;
238
+ nativeReports?.stop();
205
239
  if (utils !== undefined && previous !== undefined && utils.getGlobalHandler() === handler) {
206
240
  utils.setGlobalHandler(previous);
207
241
  }
package/dist/index.d.ts CHANGED
@@ -44,7 +44,10 @@ export declare function remoteConfig(opts?: RemoteConfigOptions): RemoteConfig;
44
44
  * stacks name the app's bundle app:///main.jsbundle (iOS) or app:///index.android.bundle
45
45
  * (Android), so the gateway finds the source maps uploaded under those names. Render errors reach
46
46
  * RUM through an error boundary: `@libo11y/rum-react`'s RumErrorBoundary, or rum.addError with
47
- * source boundary. Pass it in rum.collectors.
47
+ * source boundary. On iOS, when the app binary has the libo11y native module of
48
+ * `@libo11y/react-native`, it also records the native crashes and hangs MetricKit reports on a later
49
+ * launch (sources crash and hang), attributed to the session and screen they happened in. Pass it in
50
+ * rum.collectors.
48
51
  */
49
52
  export declare function errors(): RumCollector;
50
53
  /**
package/dist/index.js CHANGED
@@ -49,7 +49,10 @@ export function remoteConfig(opts = {}) {
49
49
  * stacks name the app's bundle app:///main.jsbundle (iOS) or app:///index.android.bundle
50
50
  * (Android), so the gateway finds the source maps uploaded under those names. Render errors reach
51
51
  * RUM through an error boundary: `@libo11y/rum-react`'s RumErrorBoundary, or rum.addError with
52
- * source boundary. Pass it in rum.collectors.
52
+ * source boundary. On iOS, when the app binary has the libo11y native module of
53
+ * `@libo11y/react-native`, it also records the native crashes and hangs MetricKit reports on a later
54
+ * launch (sources crash and hang), attributed to the session and screen they happened in. Pass it in
55
+ * rum.collectors.
53
56
  */
54
57
  export function errors() {
55
58
  return errorsWith(defaultErrorsEnv());
@@ -11,6 +11,7 @@ export { type PreloadedStorage, preloadedStorage } from "./config-cache.ts";
11
11
  export type { ErrorsEnv, ErrorUtilsLike, GlobalErrorHandler, HermesInternalLike, RejectionTrackerOptions, RumReactNativeEnv, StartupTimingLike, } from "./contracts/env.ts";
12
12
  export { type ErrorsWithOptions, errorsWith, FATAL_FLUSH_MILLIS } from "./errors.ts";
13
13
  export { bundleName, hermesStack } from "./hermes-stack.ts";
14
+ export { attributeReport, type DescribedDiagnostic, describeDiagnostic, type NativeReports, type NativeReportsDeps, nativeStack, POLL_MILLIS, startNativeReports, } from "./native-reports.ts";
14
15
  export type { ReactNativeRumTelemetry, RumReactNativeOptions, RumReactNativeSetupOptions, } from "./options.ts";
15
16
  export { screensWith } from "./screens.ts";
16
17
  export { type DeviceSessionStore, storageSessionStore } from "./session-store.ts";
package/dist/internal.js CHANGED
@@ -10,6 +10,7 @@ export { reactNativeBinding, rumLifecycle, } from "./binding.js";
10
10
  export { preloadedStorage } from "./config-cache.js";
11
11
  export { errorsWith, FATAL_FLUSH_MILLIS } from "./errors.js";
12
12
  export { bundleName, hermesStack } from "./hermes-stack.js";
13
+ export { attributeReport, describeDiagnostic, nativeStack, POLL_MILLIS, startNativeReports, } from "./native-reports.js";
13
14
  export { screensWith } from "./screens.js";
14
15
  export { storageSessionStore } from "./session-store.js";
15
16
  export { APP_LOCATION, setupRumReactNativeWith } from "./setup.js";
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Native crashes and hangs on iOS, through the libo11y native module (spec 1.4.0).
3
+ *
4
+ * MetricKit reports a crash, or a hang, to the app on a later launch, and a hang sometimes while
5
+ * its process still runs. The native module keeps a report on disk only while RUM records under
6
+ * consent (setRecording), and only when it names its process (iOS 17 and later) and that process
7
+ * wrote context under consent by the time the report's payload began. This file turns each report
8
+ * into one o11y.rum.error record and acknowledges it once the pipeline took the record and a flush
9
+ * exported it, or once it decided to drop it. A report tried again is counted once.
10
+ *
11
+ * Attribution. While RUM runs, every change of session, screen, screen name or whether the session
12
+ * is kept, and every hide (after its summaries went out), writes the current context through the
13
+ * module: session, view, the seq the view's next summary would have, whether the session is kept,
14
+ * service.version and the update ID, with the time. The module adds the process ID and start and
15
+ * keeps the last 64 entries. A report maps to the last entry its own process wrote (by process
16
+ * ID) at or before its payload ended. A report without a process ID, or whose process wrote no
17
+ * context by then, is dropped: nothing shows that process recorded under consent when it happened. A crash is never this process's; a hang may be. The
18
+ * native crash a fatal JavaScript error causes (RCTFatal) is dropped when that process marked its
19
+ * context fatal, because errors() recorded the JavaScript error already.
20
+ *
21
+ * The record carries the entry's session.id, o11y.rum.view.id, o11y.rum.app.update_id and
22
+ * service.version (else MetricKit's app version), so a crash an earlier version had is counted
23
+ * under that version, and the time the payload ended (not before the entry). It carries nothing
24
+ * current of this launch (no user.id). It retains the session when that is the current one, and
25
+ * an earlier session keeps the decision its entry recorded, so an earlier unkept session's record
26
+ * is dropped and a kept one's is sent. The error is always counted: in the view's own summary when
27
+ * it is this process's current view, else in one more summary of the entry's view (late),
28
+ * whatever the sampling. A late summary's seq follows the view's last one, and the module keeps
29
+ * the next (a late entry), so a later launch continues it.
30
+ *
31
+ * Reports arrive a moment after launch and sometimes later, so the module is read when the
32
+ * collector starts, at each of pollMillis, then every last of them until it stops. Stop on a
33
+ * revoke switches the module off, which deletes what it holds.
34
+ */
35
+ import type { Libo11yNative, NativeContextEntry, NativeDiagnostic } from "@libo11y/react-native/internal";
36
+ import type { RumRuntime } from "@libo11y/rum/core";
37
+ export { nativeStack } from "./native-stack.ts";
38
+ /**
39
+ * When the collector reads the module's reports after it starts, in milliseconds. It then reads
40
+ * them again every last of these.
41
+ */
42
+ export declare const POLL_MILLIS: readonly number[];
43
+ /** What one report becomes. */
44
+ export interface DescribedDiagnostic {
45
+ readonly source: "crash" | "hang";
46
+ readonly type: string;
47
+ readonly message: string;
48
+ readonly signal?: string;
49
+ readonly hangSeconds?: number;
50
+ readonly lines: readonly string[];
51
+ readonly images: readonly string[];
52
+ }
53
+ /**
54
+ * exception.type is the Objective-C or Swift exception name, else the Mach exception name, else the
55
+ * signal name, else NativeCrash; a hang is AppHang. The message is the exception's message, else the
56
+ * termination reason, else the exception and signal.
57
+ */
58
+ export declare function describeDiagnostic(d: NativeDiagnostic): DescribedDiagnostic;
59
+ /**
60
+ * The context a report happened in: the last entry its own process wrote at or before the
61
+ * report's payload ended, by process ID. A process ID is reused, so the process is the latest one
62
+ * with that ID that started before the end; only that choice allows for clock slack. The report
63
+ * may have happened anywhere from the payload's begin to its end, so the process must have written
64
+ * an entry at or before the begin, or stamped every entry with a first consent that early: consent
65
+ * covered the whole window. A report without a process
66
+ * ID, or whose window starts before its process's first entry, maps to nothing. A crash is never about the current
67
+ * process (currentStart); a hang may be. Late entries name no context.
68
+ */
69
+ export declare function attributeReport(d: NativeDiagnostic, history: readonly NativeContextEntry[], currentStart: number | undefined): NativeContextEntry | undefined;
70
+ /** What the reports collector needs besides the runtime. */
71
+ export interface NativeReportsDeps {
72
+ readonly native: Libo11yNative;
73
+ /**
74
+ * When to read the module's reports, in milliseconds after the start, then every last of these.
75
+ * Default POLL_MILLIS.
76
+ */
77
+ readonly pollMillis?: readonly number[];
78
+ setTimeout(cb: () => void, ms: number): unknown;
79
+ clearTimeout(handle: unknown): void;
80
+ }
81
+ /** What startNativeReports returns. */
82
+ export interface NativeReports {
83
+ /** Stops writing and reading; a revoke also switches the module off. */
84
+ stop(): void;
85
+ /**
86
+ * A fatal JavaScript error is ending the process: writes the context, after the summaries the
87
+ * crash path flushed, marked fatal, so the native crash it causes is not reported again.
88
+ * Resolves once the module has it.
89
+ */
90
+ fatal(): Promise<unknown>;
91
+ }
92
+ /** Starts writing the context and turning reports into records. */
93
+ export declare function startNativeReports(rt: RumRuntime, deps: NativeReportsDeps): NativeReports;
@@ -0,0 +1,368 @@
1
+ import { ATTR_RUM_APP_UPDATE_ID, ATTR_RUM_ERROR_BINARY_IMAGES, ATTR_RUM_ERROR_HANG_DURATION, ATTR_RUM_ERROR_SIGNAL, ATTR_RUM_ERROR_SOURCE, ATTR_RUM_VIEW_ID, EVENT_RUM_ERROR, } from "@libo11y/spec";
2
+ import { diag, ROOT_CONTEXT } from "@opentelemetry/api";
3
+ import { nativeStack } from "./native-stack.js";
4
+ export { nativeStack } from "./native-stack.js";
5
+ /**
6
+ * When the collector reads the module's reports after it starts, in milliseconds. It then reads
7
+ * them again every last of these.
8
+ */
9
+ export const POLL_MILLIS = [0, 15_000, 60_000];
10
+ /** How far after a report's payload end its process may have started (clocks differ a little). */
11
+ const SLACK_MILLIS = 60_000;
12
+ /** Mach exception names by type (mach/exception_types.h). */
13
+ const MACH_EXCEPTIONS = new Map([
14
+ [1, "EXC_BAD_ACCESS"],
15
+ [2, "EXC_BAD_INSTRUCTION"],
16
+ [3, "EXC_ARITHMETIC"],
17
+ [4, "EXC_EMULATION"],
18
+ [5, "EXC_SOFTWARE"],
19
+ [6, "EXC_BREAKPOINT"],
20
+ [7, "EXC_SYSCALL"],
21
+ [8, "EXC_MACH_SYSCALL"],
22
+ [9, "EXC_RPC_ALERT"],
23
+ [10, "EXC_CRASH"],
24
+ [11, "EXC_RESOURCE"],
25
+ [12, "EXC_GUARD"],
26
+ [13, "EXC_CORPSE_NOTIFY"],
27
+ ]);
28
+ /** POSIX signal names by number on Darwin (sys/signal.h). */
29
+ const SIGNALS = new Map([
30
+ [1, "SIGHUP"],
31
+ [2, "SIGINT"],
32
+ [3, "SIGQUIT"],
33
+ [4, "SIGILL"],
34
+ [5, "SIGTRAP"],
35
+ [6, "SIGABRT"],
36
+ [7, "SIGEMT"],
37
+ [8, "SIGFPE"],
38
+ [9, "SIGKILL"],
39
+ [10, "SIGBUS"],
40
+ [11, "SIGSEGV"],
41
+ [12, "SIGSYS"],
42
+ [13, "SIGPIPE"],
43
+ [14, "SIGALRM"],
44
+ [15, "SIGTERM"],
45
+ ]);
46
+ /**
47
+ * exception.type is the Objective-C or Swift exception name, else the Mach exception name, else the
48
+ * signal name, else NativeCrash; a hang is AppHang. The message is the exception's message, else the
49
+ * termination reason, else the exception and signal.
50
+ */
51
+ export function describeDiagnostic(d) {
52
+ const { lines, images } = nativeStack(d.callStackTree, d.kind);
53
+ if (d.kind === "hang") {
54
+ const s = d.hangSeconds;
55
+ return {
56
+ source: "hang",
57
+ type: "AppHang",
58
+ message: s === undefined ? "The main thread was unresponsive" : `The main thread was unresponsive for ${s} s`,
59
+ ...(s === undefined ? {} : { hangSeconds: s }),
60
+ lines,
61
+ images,
62
+ };
63
+ }
64
+ const signal = d.signal === undefined ? undefined : (SIGNALS.get(d.signal) ?? `SIG${d.signal}`);
65
+ const mach = d.exceptionType === undefined
66
+ ? undefined
67
+ : (MACH_EXCEPTIONS.get(d.exceptionType) ?? `EXC_${d.exceptionType}`);
68
+ const type = d.objcName ?? mach ?? signal ?? "NativeCrash";
69
+ const machText = mach === undefined
70
+ ? undefined
71
+ : `${mach}${signal === undefined ? "" : ` (${signal})`}${d.exceptionCode === undefined ? "" : `, code ${d.exceptionCode}`}`;
72
+ const message = d.objcMessage ?? d.terminationReason ?? machText ?? signal ?? "";
73
+ return { source: "crash", type, message, ...(signal === undefined ? {} : { signal }), lines, images };
74
+ }
75
+ /**
76
+ * The context a report happened in: the last entry its own process wrote at or before the
77
+ * report's payload ended, by process ID. A process ID is reused, so the process is the latest one
78
+ * with that ID that started before the end; only that choice allows for clock slack. The report
79
+ * may have happened anywhere from the payload's begin to its end, so the process must have written
80
+ * an entry at or before the begin, or stamped every entry with a first consent that early: consent
81
+ * covered the whole window. A report without a process
82
+ * ID, or whose window starts before its process's first entry, maps to nothing. A crash is never about the current
83
+ * process (currentStart); a hang may be. Late entries name no context.
84
+ */
85
+ export function attributeReport(d, history, currentStart) {
86
+ if (d.pid === undefined)
87
+ return undefined;
88
+ const latest = (es) => es.reduce((a, e) => (a === undefined || e.at >= a.at ? e : a), undefined);
89
+ const own = history.filter((e) => e.pid === d.pid &&
90
+ e.late !== true &&
91
+ (d.kind === "hang" || currentStart === undefined || e.processStart !== currentStart));
92
+ const starts = own.flatMap((e) => e.processStart !== undefined && e.processStart <= d.end + SLACK_MILLIS ? [e.processStart] : []);
93
+ const start = starts.length === 0 ? undefined : Math.max(...starts);
94
+ const proc = start === undefined ? own : own.filter((e) => e.processStart === start);
95
+ // The report may have happened anywhere in its payload's window, so the process must have
96
+ // recorded under consent from before the window began.
97
+ if (!proc.some((e) => Math.min(e.at, e.since ?? e.at) <= d.begin))
98
+ return undefined;
99
+ return latest(proc.filter((e) => e.at <= d.end));
100
+ }
101
+ /**
102
+ * Whether a crash is the abort React Native raises for a fatal JavaScript error (RCTFatal), which
103
+ * errors() already recorded as uncaught: an RCTFatalException, or a SIGABRT with no exception name
104
+ * where iOS does not report one.
105
+ */
106
+ function jsFatalAbort(d) {
107
+ if (d.objcName !== undefined)
108
+ return d.objcName.startsWith("RCTFatalException");
109
+ return d.signal === 6;
110
+ }
111
+ function resourceString(rt, key) {
112
+ try {
113
+ const v = rt.telemetry.resource?.attributes?.[key];
114
+ return typeof v === "string" && v !== "" ? v : undefined;
115
+ }
116
+ catch {
117
+ return undefined;
118
+ }
119
+ }
120
+ /** Starts writing the context and turning reports into records. */
121
+ export function startNativeReports(rt, deps) {
122
+ const { native } = deps;
123
+ const currentStart = native.processStart();
124
+ // The module keeps nothing written before it is enabled, so nothing is written until it is.
125
+ let enabled = false;
126
+ let last = "";
127
+ /** Writes the context when it changed; resolves once the module has it. */
128
+ const write = (fatal = false) => {
129
+ if (!enabled)
130
+ return Promise.resolve();
131
+ const s = rt.session.current();
132
+ const v = rt.views.current();
133
+ if (s === undefined || v === undefined)
134
+ return Promise.resolve();
135
+ const version = resourceString(rt, "service.version");
136
+ const updateId = resourceString(rt, ATTR_RUM_APP_UPDATE_ID);
137
+ const fields = {
138
+ sessionId: s.id,
139
+ viewId: v.id,
140
+ viewName: v.name,
141
+ viewKind: v.kind,
142
+ seq: rt.summary.nextSeq(v.id) ?? 0,
143
+ kept: rt.session.kept(),
144
+ ...(version === undefined ? {} : { version }),
145
+ ...(updateId === undefined ? {} : { updateId }),
146
+ };
147
+ const key = JSON.stringify(fields);
148
+ if (key === last && !fatal)
149
+ return Promise.resolve();
150
+ last = key;
151
+ return native
152
+ .recordContext({ at: rt.timeOrigin + rt.now(), ...fields, ...(fatal ? { fatal: true } : {}) })
153
+ .then((kept) => {
154
+ // A write the module refused is not the context it holds: write it again next time.
155
+ if (!kept && last === key)
156
+ last = "";
157
+ });
158
+ };
159
+ /** The next seq of each earlier view this launch sent a late summary for. */
160
+ const lateSeq = new Map();
161
+ /** The seq each report's late summary had, so a report tried again reuses it. */
162
+ const seqOf = new Map();
163
+ /**
164
+ * Records one report. False when it is dropped on purpose; a throw, as when the pipeline did not
165
+ * take the record, leaves it for the next poll. Otherwise it returns what marks the report
166
+ * counted: a late entry naming it, written only once a flush exported its summary, and resolving
167
+ * whether the module kept it. A report tried again after the mark is not counted again; one
168
+ * tried again after a failed flush, a dropped summary or a failed mark is.
169
+ */
170
+ const record = (d, history) => {
171
+ const entry = attributeReport(d, history, currentStart);
172
+ // No process ID, or one with no context: nothing shows that process recorded under consent.
173
+ if (entry === undefined)
174
+ return false;
175
+ if (entry.fatal === true && d.kind === "crash" && jsFatalAbort(d))
176
+ return false;
177
+ const described = describeDiagnostic(d);
178
+ const now = rt.timeOrigin + rt.now();
179
+ const time = Math.min(now, Math.max(d.end, entry.at));
180
+ if (entry.sessionId === rt.session.current()?.id)
181
+ rt.session.retain("error");
182
+ else if (entry.kept !== undefined)
183
+ rt.session.recall(entry.sessionId, entry.kept);
184
+ const taken = rt.emit(EVENT_RUM_ERROR, {
185
+ [ATTR_RUM_ERROR_SOURCE]: described.source,
186
+ "exception.type": described.type,
187
+ "exception.message": described.message,
188
+ ...(described.lines.length === 0
189
+ ? {}
190
+ : {
191
+ "exception.stacktrace": described.lines.join("\n"),
192
+ [ATTR_RUM_ERROR_BINARY_IMAGES]: described.images.join("\n"),
193
+ }),
194
+ ...(described.signal === undefined ? {} : { [ATTR_RUM_ERROR_SIGNAL]: described.signal }),
195
+ ...(described.hangSeconds === undefined
196
+ ? {}
197
+ : { [ATTR_RUM_ERROR_HANG_DURATION]: described.hangSeconds }),
198
+ // The app version of the launch that crashed: its context's, else what MetricKit says.
199
+ ...(() => {
200
+ const version = entry.version ?? d.appVersion ?? d.appBuild;
201
+ return version === undefined ? {} : { "service.version": version };
202
+ })(),
203
+ "session.id": entry.sessionId,
204
+ [ATTR_RUM_VIEW_ID]: entry.viewId,
205
+ ...(entry.updateId === undefined ? {} : { [ATTR_RUM_APP_UPDATE_ID]: entry.updateId }),
206
+ }, ROOT_CONTEXT, undefined, time);
207
+ if (!taken)
208
+ throw new Error("the record did not reach the log export");
209
+ if (history.some((e) => e.late === true && e.report === d.id))
210
+ return async () => true;
211
+ const key = `errors.${described.source}`;
212
+ const view = { viewId: entry.viewId, viewName: entry.viewName, viewKind: entry.viewKind };
213
+ const mark = (seq) => () => native.recordContext({
214
+ at: now,
215
+ sessionId: entry.sessionId,
216
+ ...view,
217
+ seq,
218
+ late: true,
219
+ report: d.id,
220
+ });
221
+ // A hang of this process in the screen still current counts in that screen's own summary,
222
+ // sent now so the flush that follows exports it.
223
+ if (entry.processStart === currentStart && entry.viewId === rt.views.current()?.id) {
224
+ rt.summary.count(key);
225
+ if (!rt.summary.flush())
226
+ throw new Error("the summary did not reach the log export");
227
+ return mark(rt.summary.nextSeq(entry.viewId) ?? 0);
228
+ }
229
+ // The view's latest seq: its process's entries, a late summary a launch sent, and this
230
+ // process's own count when the view is one of its own.
231
+ const written = history
232
+ .filter((e) => e.viewId === entry.viewId && (e.processStart === entry.processStart || e.late === true))
233
+ .reduce((m, e) => Math.max(m, e.seq), entry.seq);
234
+ const seq = seqOf.get(d.id) ??
235
+ Math.max(written, lateSeq.get(entry.viewId) ?? 0, rt.summary.nextSeq(entry.viewId) ?? 0);
236
+ seqOf.set(d.id, seq);
237
+ lateSeq.set(entry.viewId, Math.max(lateSeq.get(entry.viewId) ?? 0, seq + 1));
238
+ const counted = rt.summary.late({
239
+ id: entry.viewId,
240
+ name: entry.viewName,
241
+ kind: entry.viewKind,
242
+ sessionId: entry.sessionId,
243
+ }, seq, key);
244
+ if (!counted)
245
+ throw new Error("the summary did not reach the log export");
246
+ return mark(seq + 1);
247
+ };
248
+ let stopped = false;
249
+ let polling = false;
250
+ const poll = async () => {
251
+ if (stopped || polling || !enabled)
252
+ return;
253
+ polling = true;
254
+ try {
255
+ write();
256
+ const pending = await native.pendingDiagnostics();
257
+ if (stopped || pending.length === 0)
258
+ return;
259
+ const history = await native.contextHistory();
260
+ if (stopped)
261
+ return;
262
+ const dropped = [];
263
+ const recorded = [];
264
+ const marks = [];
265
+ for (const d of pending) {
266
+ try {
267
+ const mark = record(d, history);
268
+ if (mark === false)
269
+ dropped.push(d.id);
270
+ else {
271
+ recorded.push(d.id);
272
+ marks.push(mark);
273
+ }
274
+ }
275
+ catch (err) {
276
+ // Kept for the next poll.
277
+ diag.warn("o11y: rum: recording a native report failed", err);
278
+ }
279
+ }
280
+ // A recorded report is marked counted and acknowledged once a flush exported its record and
281
+ // summary to delivery or its retry queue, so a crash before the export does not lose it.
282
+ let delivered = recorded.length > 0;
283
+ if (delivered) {
284
+ const report = await rt.telemetry.forceFlush();
285
+ delivered = !report.errors.some((e) => e.signal === "logs" || e.signal === "lifecycle");
286
+ }
287
+ // A revoke while this poll waited ends it: what a later grant's module holds is not this
288
+ // grant's to mark or acknowledge.
289
+ if (stopped)
290
+ return;
291
+ // A report is acknowledged once its mark is on disk, so a later launch never counts it again.
292
+ const marked = delivered ? await Promise.all(marks.map((mark) => mark())) : [];
293
+ if (stopped)
294
+ return;
295
+ native.acknowledgeDiagnostics([...dropped, ...recorded.filter((_, i) => marked[i] === true)]);
296
+ }
297
+ catch (err) {
298
+ diag.warn("o11y: rum: reading native reports failed", err);
299
+ }
300
+ finally {
301
+ polling = false;
302
+ }
303
+ };
304
+ const delays = deps.pollMillis ?? POLL_MILLIS;
305
+ const every = delays.at(-1) ?? 0;
306
+ const timers = new Set();
307
+ const later = (ms, then) => {
308
+ const t = deps.setTimeout(() => {
309
+ timers.delete(t);
310
+ if (!stopped)
311
+ then();
312
+ }, ms);
313
+ timers.add(t);
314
+ };
315
+ const repeat = () => {
316
+ void poll();
317
+ if (every > 0)
318
+ later(every, repeat);
319
+ };
320
+ for (const [i, ms] of delays.entries()) {
321
+ later(ms, i === delays.length - 1 ? repeat : () => void poll());
322
+ }
323
+ native.setRecording(true).then(() => {
324
+ if (stopped)
325
+ return;
326
+ enabled = true;
327
+ write();
328
+ // The startup poll, when the timer for it fired before the module was enabled.
329
+ void poll();
330
+ }, (err) => diag.warn("o11y: rum: the native module could not start recording", err));
331
+ const offViews = rt.views.subscribe((e) => {
332
+ if (e.type === "start" || e.type === "rename")
333
+ write();
334
+ });
335
+ const offSession = rt.session.subscribe((e) => {
336
+ if (e.type === "start" || e.type === "kept")
337
+ write();
338
+ });
339
+ // A hide sends the summaries after its hooks run, so the context is written after them.
340
+ let hideTimer;
341
+ const offHide = rt.onHide(() => {
342
+ deps.clearTimeout(hideTimer);
343
+ hideTimer = deps.setTimeout(write, 0);
344
+ });
345
+ return {
346
+ stop() {
347
+ stopped = true;
348
+ for (const t of timers)
349
+ deps.clearTimeout(t);
350
+ timers.clear();
351
+ deps.clearTimeout(hideTimer);
352
+ offViews();
353
+ offSession();
354
+ offHide();
355
+ // A revoke closes the gate before the collectors stop: the module stops keeping reports and
356
+ // deletes what it holds. A shutdown or remote configuration leaves it recording; errors()'s
357
+ // clear switches it off on a revoke or a denied start when the collector is not running.
358
+ if (!rt.gate.recording()) {
359
+ native
360
+ .setRecording(false)
361
+ .catch((err) => diag.warn("o11y: rum: the native module could not delete what it holds", err));
362
+ }
363
+ },
364
+ fatal() {
365
+ return stopped ? Promise.resolve() : write(true);
366
+ },
367
+ };
368
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The native stack format of spec 1.4.0, built from MetricKit's call stack tree. It imports nothing,
3
+ * so the gateway journey and other tools can build a stack exactly as errors() does.
4
+ */
5
+ /**
6
+ * The stack of the thread MetricKit attributes the report to (else the first), innermost first, in
7
+ * the spec's native format, and one `<UUID> <load address> <name>` line per binary in it. Both stay
8
+ * under the gateway's value limit: the stack is cut at a frame boundary, and only the images of the
9
+ * kept frames are listed. kind says how MetricKit laid the tree out (framesOf).
10
+ */
11
+ export declare function nativeStack(tree: unknown, kind?: "crash" | "hang"): {
12
+ lines: string[];
13
+ images: string[];
14
+ };
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The native stack format of spec 1.4.0, built from MetricKit's call stack tree. It imports nothing,
3
+ * so the gateway journey and other tools can build a stack exactly as errors() does.
4
+ */
5
+ /** The gateway's default limit on one attribute value, which the stack and images stay under. */
6
+ const MAX_VALUE_BYTES = 4096;
7
+ /** The most frames a native stack keeps. */
8
+ const MAX_FRAMES = 64;
9
+ /** The most nested frames read from one MetricKit tree, against a malformed or cyclic payload. */
10
+ const MAX_DEPTH = 512;
11
+ const isObject = (v) => typeof v === "object" && v !== null;
12
+ const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
13
+ function frameOf(v) {
14
+ if (!isObject(v))
15
+ return undefined;
16
+ const { binaryUUID, binaryName, address, offsetIntoBinaryTextSegment: offset } = v;
17
+ if (typeof binaryUUID !== "string" || binaryUUID === "" || !isCount(offset))
18
+ return undefined;
19
+ const name = typeof binaryName === "string" && binaryName !== "" ? binaryName.replace(/\s+/g, " ") : "???";
20
+ return { uuid: binaryUUID.toUpperCase(), name, address: isCount(address) ? address : offset, offset };
21
+ }
22
+ const subFramesOf = (node) => isObject(node) && Array.isArray(node.subFrames) ? node.subFrames : [];
23
+ const samplesOf = (node) => isObject(node) && isCount(node.sampleCount) ? node.sampleCount : 0;
24
+ /** The most sampled of nodes, the first on a tie. */
25
+ const mostSampled = (nodes) => nodes.reduce((best, n) => (best === undefined || samplesOf(n) > samplesOf(best) ? n : best), undefined);
26
+ /**
27
+ * The frames of one MetricKit call stack, innermost first. A crash's stack starts at the crashed
28
+ * frame and nests each caller as its first subframe. A hang's is the main thread's samples
29
+ * aggregated from the outermost frame (dyld's start), nesting the callees of each frame, which
30
+ * branch where samples differ: its stack is the most sampled path, reversed.
31
+ */
32
+ function framesOf(stack, kind) {
33
+ const out = [];
34
+ const roots = isObject(stack) && Array.isArray(stack.callStackRootFrames) ? stack.callStackRootFrames : [];
35
+ const next = kind === "hang" ? mostSampled : (nodes) => nodes[0];
36
+ let node = next(roots);
37
+ for (let depth = 0; node !== undefined && depth < MAX_DEPTH; depth++) {
38
+ const f = frameOf(node);
39
+ if (f === undefined)
40
+ break;
41
+ out.push(f);
42
+ node = next(subFramesOf(node));
43
+ }
44
+ return kind === "hang" ? out.reverse() : out;
45
+ }
46
+ const hex = (n) => n.toString(16);
47
+ const loadOf = (f) => Math.max(0, f.address - f.offset);
48
+ function frameLine(i, f) {
49
+ return `${String(i).padEnd(3)} ${f.name.padEnd(30)} 0x${hex(f.address).padStart(16, "0")} 0x${hex(loadOf(f))} + ${f.offset}`;
50
+ }
51
+ /**
52
+ * The stack of the thread MetricKit attributes the report to (else the first), innermost first, in
53
+ * the spec's native format, and one `<UUID> <load address> <name>` line per binary in it. Both stay
54
+ * under the gateway's value limit: the stack is cut at a frame boundary, and only the images of the
55
+ * kept frames are listed. kind says how MetricKit laid the tree out (framesOf).
56
+ */
57
+ export function nativeStack(tree, kind = "crash") {
58
+ const stacks = isObject(tree) && Array.isArray(tree.callStacks) ? tree.callStacks : [];
59
+ const stack = stacks.find((s) => isObject(s) && s.threadAttributed === true) ?? stacks[0];
60
+ const lines = [];
61
+ const images = [];
62
+ const seen = new Set();
63
+ let lineBytes = 0;
64
+ let imageBytes = 0;
65
+ for (const [i, f] of framesOf(stack, kind).slice(0, MAX_FRAMES).entries()) {
66
+ const line = frameLine(i, f);
67
+ const image = seen.has(f.uuid) ? undefined : `${f.uuid} 0x${hex(loadOf(f))} ${f.name}`;
68
+ const addImage = image === undefined ? 0 : image.length + (images.length > 0 ? 1 : 0);
69
+ const addLine = line.length + (lines.length > 0 ? 1 : 0);
70
+ if (lineBytes + addLine > MAX_VALUE_BYTES || imageBytes + addImage > MAX_VALUE_BYTES)
71
+ break;
72
+ lines.push(line);
73
+ lineBytes += addLine;
74
+ if (image !== undefined) {
75
+ seen.add(f.uuid);
76
+ images.push(image);
77
+ imageBytes += addImage;
78
+ }
79
+ }
80
+ return { lines, images };
81
+ }
package/dist/setup.js CHANGED
@@ -26,7 +26,7 @@ export async function setupRumReactNativeWith(options, deps, install) {
26
26
  const { rum: rumOptions = {}, ...platformOptions } = options;
27
27
  const { initialViewName = "app", ...core } = rumOptions;
28
28
  const storage = platformOptions.storage ?? memoryStorage();
29
- const appStart = createAppStart({ env: deps.env, now: deps.perfNow });
29
+ const appStart = createAppStart({ env: deps.env, now: deps.perfNow, timeOrigin: deps.timeOrigin });
30
30
  /** Activity listeners RUM's core registered: a new screen is the user moving through the app. */
31
31
  const activity = new Set();
32
32
  const t = await setupRumCore({ ...platformOptions, storage }, { ...core, viewName: () => initialViewName }, {
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The `@libo11y/rum-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.8.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The `@libo11y/rum-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.8.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libo11y/rum-react-native",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "libo11y RUM for React Native apps on Hermes: sessions that survive a relaunch, consent, session sampling with a retention buffer on device storage, screens, the app_load span and per-screen summaries over @libo11y/react-native. The handle works with @libo11y/rum-react and @libo11y/rum-connect.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -25,11 +25,11 @@
25
25
  "directory": "ts/packages/rum-react-native"
26
26
  },
27
27
  "dependencies": {
28
- "@libo11y/core": "0.6.0",
29
- "@libo11y/react-native": "0.6.0",
30
- "@libo11y/rum": "0.6.0",
31
- "@libo11y/spec": "0.6.0",
32
- "@libo11y/web": "0.6.0"
28
+ "@libo11y/core": "0.8.0",
29
+ "@libo11y/react-native": "0.8.0",
30
+ "@libo11y/rum": "0.8.0",
31
+ "@libo11y/spec": "0.8.0",
32
+ "@libo11y/web": "0.8.0"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "@opentelemetry/api": ">=1.10.0 <1.11.0",
@@ -37,9 +37,9 @@
37
37
  "react-native": ">=0.88.0"
38
38
  },
39
39
  "devDependencies": {
40
- "@libo11y/rum-connect": "0.6.0",
41
- "@libo11y/rum-react": "0.6.0",
42
- "@libo11y/test": "0.6.0",
40
+ "@libo11y/rum-connect": "0.8.0",
41
+ "@libo11y/rum-react": "0.8.0",
42
+ "@libo11y/test": "0.8.0",
43
43
  "@opentelemetry/api": "1.10.0",
44
44
  "@opentelemetry/sdk-trace": "3.1.1",
45
45
  "@types/react": "19.3.0",