@libo11y/rum-react-native 0.0.0-stage → 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.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The app_load span on React Native: once per process, the app's start until its
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
7
+ * rum.viewRendered here, consent or not, so the first screen's render is known even when consent
8
+ * comes later or after other screens. app_load is recorded when the first grant of the process
9
+ * begins the load view, with its session.id and view ID, and is the load view span's parent
10
+ * (appLoadStarted). It ends at the first screen's render, or capMillis after its start without one,
11
+ * as when the app moved to another screen before the first rendered.
12
+ */
13
+ import { APP_LOAD_SPAN, ATTR_SESSION_ID } from "@libo11y/rum/core";
14
+ import { ATTR_RUM_PLATFORM, ATTR_RUM_SPAN_SHAPE, ATTR_RUM_VIEW_ID, RUM_SPAN_SHAPE_VALUE_APP_LOAD, } from "@libo11y/spec";
15
+ import { ROOT_CONTEXT, SpanKind } from "@opentelemetry/api";
16
+ /** app_load ends this long after it started at the latest. */
17
+ export const APP_LOAD_CAP_MILLIS = 60_000;
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;
30
+ const s = env.startupTiming?.startTime;
31
+ return usable(s, now) ? s : env.loadedAt;
32
+ }
33
+ export function createAppStart(o) {
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;
37
+ let recorded = false;
38
+ /** The first screen was left before it rendered. */
39
+ let left = false;
40
+ let firstRender;
41
+ let timer;
42
+ let off;
43
+ /** Ends the open app_load at a performance.now() time, within its start and cap. */
44
+ let end;
45
+ const record = (rt, viewId, sessionId) => {
46
+ recorded = true;
47
+ const span = rt.tracer.startSpan(APP_LOAD_SPAN, {
48
+ kind: SpanKind.INTERNAL,
49
+ startTime: rt.timeOrigin + start,
50
+ attributes: {
51
+ [ATTR_RUM_SPAN_SHAPE]: RUM_SPAN_SHAPE_VALUE_APP_LOAD,
52
+ [ATTR_RUM_PLATFORM]: rt.platform,
53
+ [ATTR_RUM_VIEW_ID]: viewId,
54
+ [ATTR_SESSION_ID]: sessionId,
55
+ },
56
+ }, ROOT_CONTEXT);
57
+ rt.views.appLoadStarted(span.spanContext());
58
+ end = (at) => {
59
+ end = undefined;
60
+ o.env.clearTimeout(timer);
61
+ span.end(rt.timeOrigin + Math.max(start, Math.min(at, capAt)));
62
+ };
63
+ if (firstRender !== undefined)
64
+ end(firstRender);
65
+ else
66
+ timer = o.env.setTimeout(() => end?.(capAt), Math.max(0, capAt - o.now()));
67
+ };
68
+ return {
69
+ start,
70
+ attach(rt) {
71
+ off?.();
72
+ off = rt.views.subscribe((e) => {
73
+ if (e.type !== "start" || recorded || e.view.id !== rt.views.loadView()?.id)
74
+ return;
75
+ record(rt, e.view.id, e.view.sessionId);
76
+ });
77
+ },
78
+ screenStarted() {
79
+ left = true;
80
+ },
81
+ rendered(at) {
82
+ if (left || firstRender !== undefined)
83
+ return;
84
+ firstRender = at;
85
+ end?.(at);
86
+ },
87
+ close() {
88
+ off?.();
89
+ off = undefined;
90
+ end?.(o.now());
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The React Native binding of the RUM core: setupRumCore hands it the setup options with
3
+ * RUM's span processor, context manager and forwarding span exporter in place, and the wrappers;
4
+ * it runs `@libo11y/react-native`'s setupReactNativeWith over deps with each wrapper applied. The
5
+ * lifecycle is the app's AppState: background, and inactive on iOS, hide the app; active shows it.
6
+ */
7
+ import type { ReactNativeSetupOptions, ReactNativeTelemetry } from "@libo11y/react-native";
8
+ import { type AppLifecycle, type ReactNativeDeps } from "@libo11y/react-native/internal";
9
+ import type { RumBind, RumLifecycle } from "@libo11y/rum/core";
10
+ /** A binding of React Native: its setup options and telemetry. */
11
+ export type ReactNativeRumBind = RumBind<ReactNativeSetupOptions, ReactNativeTelemetry>;
12
+ /** How the binding runs the platform. */
13
+ export interface ReactNativeBindingOptions {
14
+ /** Install the telemetry globally, as setupReactNative does. */
15
+ readonly install: boolean;
16
+ /** The fetch the OTLP transport sends with instead of the pristine global fetch, as in tests. */
17
+ readonly fetch?: typeof globalThis.fetch;
18
+ }
19
+ /** The React Native binding: setupReactNativeWith over deps with RUM's wrappers. */
20
+ export declare function reactNativeBinding(deps: ReactNativeDeps, o: ReactNativeBindingOptions): ReactNativeRumBind;
21
+ /**
22
+ * RUM's lifecycle over the app's: hide on going to the background, show on coming back. RUM
23
+ * subscribes before the binding runs the platform's setup, so on a hide the summaries are emitted
24
+ * before the platform's own listener flushes them. No restore: an app has no back/forward cache.
25
+ * The setup adds activity: a new screen, until the touch boundary records touches.
26
+ */
27
+ export declare function rumLifecycle(app: AppLifecycle): RumLifecycle;
@@ -0,0 +1,31 @@
1
+ import { setupReactNativeWith, } from "@libo11y/react-native/internal";
2
+ /** The React Native binding: setupReactNativeWith over deps with RUM's wrappers. */
3
+ export function reactNativeBinding(deps, o) {
4
+ const fetch = o.fetch;
5
+ return (options, w) => setupReactNativeWith(options, {
6
+ ...deps,
7
+ createConsentController: (co) => w.consentController(deps.createConsentController(co)),
8
+ createHttpTransport: (t) => deps.createHttpTransport(w.transportOptions(fetch === undefined ? t : { ...t, fetch })),
9
+ // Traces are injected, so the platform's span exporter goes unused; logs are routed by
10
+ // session. The gateway accepts only delta sums and histograms, so app metrics export with
11
+ // delta temporality.
12
+ createExporterSet: (req, d, endpoints, eo) => w.exporterSet(deps.createExporterSet(req, d, endpoints, { ...eo, metricTemporality: "delta" })),
13
+ installNetworkInstrumentation: (n) => deps.installNetworkInstrumentation({ ...n, onStart: w.onRequestStart }),
14
+ onPlatform: (platform, info) => {
15
+ w.platform({ delivery: info.delivery, endpoints: info.endpoints }, info.env);
16
+ deps.onPlatform?.(platform, info);
17
+ },
18
+ }, o.install);
19
+ }
20
+ /**
21
+ * RUM's lifecycle over the app's: hide on going to the background, show on coming back. RUM
22
+ * subscribes before the binding runs the platform's setup, so on a hide the summaries are emitted
23
+ * before the platform's own listener flushes them. No restore: an app has no back/forward cache.
24
+ * The setup adds activity: a new screen, until the touch boundary records touches.
25
+ */
26
+ export function rumLifecycle(app) {
27
+ return {
28
+ visible: () => app.visible(),
29
+ subscribe: (h) => app.subscribe((visible) => (visible ? h.show() : h.hide())),
30
+ };
31
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The remote configuration cache on device storage. The remote configuration client reads its
3
+ * cache synchronously (localStorage on the web), and device storage is asynchronous, so the cache
4
+ * reads the listed keys once, when RUM opens remote configuration on the first grant, and serves
5
+ * them from memory. Writes change memory at once and reach storage in the background, one after
6
+ * another in call order; a failed write keeps the value for this run only.
7
+ */
8
+ import type { KeyValueStorage } from "@libo11y/react-native";
9
+ import type { ConfigCacheStorage } from "@libo11y/rum/core";
10
+ /** The remote configuration cache over device storage, whose background writes can be awaited. */
11
+ export interface PreloadedStorage extends ConfigCacheStorage {
12
+ /**
13
+ * Resolves once every write already made has reached storage or failed. A failed write was
14
+ * reported through diag when it failed. Never rejects.
15
+ */
16
+ flush(): Promise<void>;
17
+ }
18
+ /** A synchronous cache of keys over storage, once their stored values are read. Never rejects. */
19
+ export declare function preloadedStorage(storage: KeyValueStorage, keys: readonly string[]): Promise<PreloadedStorage>;
@@ -0,0 +1,38 @@
1
+ import { diag } from "@opentelemetry/api";
2
+ /** A synchronous cache of keys over storage, once their stored values are read. Never rejects. */
3
+ export async function preloadedStorage(storage, keys) {
4
+ const allowed = new Set(keys);
5
+ const values = new Map();
6
+ for (const k of allowed) {
7
+ try {
8
+ const v = await storage.getItem(k);
9
+ if (v !== null)
10
+ values.set(k, v);
11
+ }
12
+ catch (err) {
13
+ diag.debug("o11y: rum: remote configuration cache unreadable", err);
14
+ }
15
+ }
16
+ let last = Promise.resolve();
17
+ const background = (write) => {
18
+ last = last
19
+ .then(write)
20
+ .catch((err) => diag.debug("o11y: rum: remote configuration cache write failed", err));
21
+ };
22
+ return {
23
+ getItem: (k) => (allowed.has(k) ? (values.get(k) ?? null) : null),
24
+ setItem(k, v) {
25
+ if (!allowed.has(k))
26
+ return;
27
+ values.set(k, v);
28
+ background(() => storage.setItem(k, v));
29
+ },
30
+ removeItem(k) {
31
+ if (!allowed.has(k))
32
+ return;
33
+ values.delete(k);
34
+ background(() => storage.removeItem(k));
35
+ },
36
+ flush: () => last,
37
+ };
38
+ }
@@ -0,0 +1,73 @@
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
+ import type { Libo11yNative } from "@libo11y/react-native/internal";
6
+ /** React Native's performance.rnStartupTiming, in performance.now() time. */
7
+ export interface StartupTimingLike {
8
+ /** When the native process started, as React Native measures it. */
9
+ readonly startTime?: number;
10
+ readonly endTime?: number;
11
+ }
12
+ /** What the React Native RUM collectors read from the runtime. */
13
+ export interface RumReactNativeEnv {
14
+ /** performance.rnStartupTiming, where the runtime has it. */
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;
21
+ /** performance.now() when `@libo11y/rum-react-native` was first evaluated: the app start fallback. */
22
+ readonly loadedAt: number;
23
+ /** False while the app is in the background, or inactive on iOS. */
24
+ visible(): boolean;
25
+ requestAnimationFrame(cb: () => void): unknown;
26
+ setTimeout(cb: () => void, ms: number): unknown;
27
+ clearTimeout(handle: unknown): void;
28
+ }
29
+ /** React Native's global error handler, as ErrorUtils.setGlobalHandler takes it. */
30
+ export type GlobalErrorHandler = (error: unknown, isFatal?: boolean) => void;
31
+ /** The part of React Native's global ErrorUtils the errors collector uses. */
32
+ export interface ErrorUtilsLike {
33
+ /** The handler installed now. */
34
+ getGlobalHandler(): GlobalErrorHandler | undefined;
35
+ /** Replaces the installed handler. */
36
+ setGlobalHandler(handler: GlobalErrorHandler): void;
37
+ }
38
+ /** The options of Hermes' promise rejection tracker, as the promise library's rejection tracking takes them. */
39
+ export interface RejectionTrackerOptions {
40
+ /** Track every rejection, not only those of an Error. */
41
+ readonly allRejections: boolean;
42
+ /** A rejection had no handler when the engine checked. */
43
+ onUnhandled(id: number, rejection: unknown): void;
44
+ /** A rejection onUnhandled reported got a handler later. */
45
+ onHandled(id: number): void;
46
+ }
47
+ /** The part of the HermesInternal global the errors collector uses. */
48
+ export interface HermesInternalLike {
49
+ /** Replaces the tracker any earlier call set up, React Native's development one included. */
50
+ enablePromiseRejectionTracker?(options: RejectionTrackerOptions): void;
51
+ }
52
+ /** What the errors collector reads from the runtime. */
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;
59
+ /** The ErrorUtils global, absent outside React Native. */
60
+ readonly errorUtils?: ErrorUtilsLike;
61
+ /** The HermesInternal global, absent on another engine. */
62
+ readonly hermes?: HermesInternalLike;
63
+ /** Platform.OS: the bundle stack frames are named after. */
64
+ readonly os: string;
65
+ /** __DEV__: a development build, whose stacks point at Metro and whose fatal errors show the red box at once. */
66
+ readonly dev: boolean;
67
+ /** console.warn, for React Native's development note on a rejection handled late. */
68
+ warn(message: string): void;
69
+ /** The runtime's setTimeout, for the fatal error deadline. */
70
+ setTimeout(cb: () => void, ms: number): unknown;
71
+ /** The runtime's clearTimeout. */
72
+ clearTimeout(handle: unknown): void;
73
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/env.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { type AppLifecycle } from "@libo11y/react-native/internal";
2
+ import type { SettleTimers } from "@libo11y/rum/core";
3
+ import type { ErrorsEnv, RumReactNativeEnv } from "./contracts/env.ts";
4
+ import type { RumReactNativeDeps } from "./setup.ts";
5
+ /** React Native's frames, timers and startup timing, with the app's lifecycle for visible. */
6
+ export declare function defaultRumEnv(lifecycle?: AppLifecycle): RumReactNativeEnv;
7
+ /** The runtime's timers. */
8
+ export declare const runtimeTimers: SettleTimers;
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
+ */
13
+ export declare function defaultErrorsEnv(): ErrorsEnv;
14
+ /** The real dependencies of setupRumReactNativeWith. */
15
+ export declare function defaultRumReactNativeDeps(): RumReactNativeDeps;
package/dist/env.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The real React Native dependencies of setupRumReactNative and screens(). The only module of the
3
+ * main entry that reads React Native's globals and, through `@libo11y/react-native/env`, loads
4
+ * react-native, so node tests never load it (boundary.test.ts enforces that).
5
+ */
6
+ import { defaultReactNativeDeps, defaultReactNativeEnv } from "@libo11y/react-native/env";
7
+ import { appStateLifecycle, libo11yNative } from "@libo11y/react-native/internal";
8
+ const perf = globalThis
9
+ .performance;
10
+ /** performance.now() when this module was first evaluated: the app start without rnStartupTiming. */
11
+ const LOADED_AT = perf?.now() ?? 0;
12
+ /** React Native's frames, timers and startup timing, with the app's lifecycle for visible. */
13
+ export function defaultRumEnv(lifecycle = appStateLifecycle(defaultReactNativeEnv().appState)) {
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();
18
+ return {
19
+ ...(startup === undefined ? {} : { startupTiming: startup }),
20
+ ...(processStart === undefined ? {} : { processStart }),
21
+ loadedAt: LOADED_AT,
22
+ visible: () => lifecycle.visible(),
23
+ requestAnimationFrame: (cb) => requestAnimationFrame(cb),
24
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
25
+ clearTimeout: (h) => clearTimeout(h),
26
+ };
27
+ }
28
+ /** The runtime's timers. */
29
+ export const runtimeTimers = {
30
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
31
+ clearTimeout: (h) => clearTimeout(h),
32
+ };
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
+ */
37
+ export function defaultErrorsEnv() {
38
+ const g = globalThis;
39
+ const rn = defaultReactNativeEnv();
40
+ const native = libo11yNative();
41
+ return {
42
+ ...(native === undefined ? {} : { native }),
43
+ ...(g.ErrorUtils == null ? {} : { errorUtils: g.ErrorUtils }),
44
+ ...(g.HermesInternal == null ? {} : { hermes: g.HermesInternal }),
45
+ os: rn.os,
46
+ dev: rn.dev,
47
+ warn: (m) => console.warn(m),
48
+ ...runtimeTimers,
49
+ };
50
+ }
51
+ /** The real dependencies of setupRumReactNativeWith. */
52
+ export function defaultRumReactNativeDeps() {
53
+ const platform = defaultReactNativeDeps();
54
+ const now = () => perf?.now() ?? Date.now();
55
+ return {
56
+ platform,
57
+ env: defaultRumEnv(platform.lifecycle),
58
+ now: Date.now,
59
+ perfNow: now,
60
+ // React Native has performance.timeOrigin; a runtime without it counts from now.
61
+ timeOrigin: typeof perf?.timeOrigin === "number" ? perf.timeOrigin : Date.now() - now(),
62
+ };
63
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * errors(): JavaScript errors on React Native.
3
+ *
4
+ * Sources. An error React Native's global handler receives (ErrorUtils.setGlobalHandler) is
5
+ * uncaught: the collector records it and hands it to the handler that was installed before it,
6
+ * always, so the red box, LogBox and the crash still happen. A fatal error in a release build is
7
+ * about to end the process, so the current screen's summary is emitted and the telemetry flushed
8
+ * (React Native telemetry saves every batch on device storage before it sends it) before the
9
+ * previous handler runs, for at most fatalFlushMillis. A fatal error while one is waiting is
10
+ * recorded and handed on after it, in order. When the previous handler throws there, the throw
11
+ * is raised again from a task, so it still ends the app; the crash path runs once, and fatal
12
+ * errors after it, the raised throw included (not recorded again), go straight to the previous
13
+ * handler. In development the previous handler runs at once.
14
+ *
15
+ * Hermes reports unhandled promise rejections only to the tracker HermesInternal's
16
+ * enablePromiseRejectionTracker sets, which React Native turns on in development alone, and a
17
+ * second call replaces the first. The collector sets one with allRejections: each unhandled
18
+ * rejection is unhandled_rejection, and in development the tracker also does what React Native's
19
+ * does, through the previous global handler (the red box path) and console.warn. Another engine
20
+ * reports no rejections.
21
+ *
22
+ * A request that ends without a status is network, type NetworkError, message "<METHOD> <host>
23
+ * failed", unless the app aborted it, as in the browser's errors().
24
+ *
25
+ * React renders errors through an error boundary, never this handler: `@libo11y/rum-react`'s
26
+ * RumErrorBoundary, or an app's own boundary calling rum.addError with source boundary.
27
+ *
28
+ * Stacks. In a release build Hermes names the bundle by its path on the device, sometimes after
29
+ * "address at ". Each frame of the app's bundle is rewritten to app:///main.jsbundle (iOS) or
30
+ * app:///index.android.bundle (Android), so the gateway finds the source map uploaded under that
31
+ * name for the app's service.version and o11y.rum.app.update_id, and no device path leaves the
32
+ * phone. Engine frames (native, InternalBytecode.js) are kept. Development stacks point at Metro
33
+ * and are kept as they are.
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
+ *
40
+ * Every error goes through recordError, so it counts in the screen's summary, retains an unsampled
41
+ * session, and carries the breadcrumbs. An error raised while one is being recorded is not recorded
42
+ * again. Stop restores the previous global handler while RUM's is still the installed one; a
43
+ * handler installed over RUM's keeps calling it, and it then only passes errors on.
44
+ */
45
+ import { type RumCollector } from "@libo11y/rum/core";
46
+ import type { ErrorsEnv } from "./contracts/env.ts";
47
+ /** How long a fatal error in a release build waits for the flush before it reaches the previous handler. */
48
+ export declare const FATAL_FLUSH_MILLIS = 2000;
49
+ /** Internal options of errorsWith, for tests. */
50
+ export interface ErrorsWithOptions {
51
+ /** Default FATAL_FLUSH_MILLIS. */
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[];
55
+ }
56
+ /** The errors collector over env. */
57
+ export declare function errorsWith(env: ErrorsEnv, o?: ErrorsWithOptions): RumCollector;