Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ android/keystores/debug.keystore
# generated by bob
lib/

# Vite
# web builds (expo export)
dist/

# React Native Codegen
Expand All @@ -89,3 +89,8 @@ android/generated
.superpowers/
verify/artifacts/
verify/e2e/.e2e/

# SwiftPM (Package.swift: ios/Core tests)
.build/
.swiftpm/
/Package.resolved
11 changes: 10 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,16 @@ module.exports = {
'<rootDir>/verify/harness/**/*.test.ts',
],
},
{
displayName: 'unit',
testEnvironment: 'node',
transform,
testMatch: [
'<rootDir>/src/**/__tests__/**/*.test.[jt]s',
'<rootDir>/metro/__tests__/**/*.test.[jt]s',
],
},
'<rootDir>/verify/jest/jest.scenarios.config.js',
// fixtures, degraded projects live under verify/jest/ (later tasks)
// the degraded project lives under verify/jest/ (later task)
],
};
43 changes: 43 additions & 0 deletions metro/__tests__/withOtel.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const {withOtel} = require('..');

// Stubbed so the test does not depend on a built lib/ (self-reference via `exports`).
const SETUP = '/pkg/lib/module/setup.js';
const run = config => withOtel(config, {setupPath: SETUP}).serializer.getModulesRunBeforeMainModule('/app/index.js');
const CORE = '/rn/Libraries/Core/InitializeCore.js';
const base = {serializer: {getModulesRunBeforeMainModule: () => [CORE]}, resolver: {x: 1}};

test('adds setup after InitializeCore', () => {
expect(run(base)).toEqual([CORE, SETUP]);
});

test("keeps a user's existing entries", () => {
const cfg = {...base, serializer: {getModulesRunBeforeMainModule: () => [CORE, '/app/polyfill.js'], other: 2}};
const out = withOtel(cfg, {setupPath: SETUP});
expect(run(cfg)).toEqual([CORE, '/app/polyfill.js', SETUP]);
expect(out.serializer.other).toBe(2);
expect(out.resolver).toEqual({x: 1});
});

test('is idempotent when applied twice', () => {
const once = withOtel(base, {setupPath: SETUP});
expect(run(withOtel(once, {setupPath: SETUP}))).toEqual([CORE, SETUP]);
});

test('keeps the package out of inline requires, after the existing entries', async () => {
const cfg = {
...base,
transformer: {
getTransformOptions: async () => ({transform: {inlineRequires: true, nonInlinedRequires: ['React']}, x: 1}),
},
};
const out = await withOtel(cfg, {setupPath: SETUP}).transformer.getTransformOptions([], {}, () => []);
expect(out).toEqual({transform: {inlineRequires: true, nonInlinedRequires: ['React', 'react-native-open-telemetry']}, x: 1});
const bare = await withOtel(base, {setupPath: SETUP}).transformer.getTransformOptions([], {}, () => []);
expect(bare.transform.nonInlinedRequires).toEqual(['react-native-open-telemetry']);
});

test('throws on an unmerged config instead of dropping InitializeCore', () => {
expect(() => withOtel({resolver: {x: 1}}, {setupPath: SETUP})).toThrow(
'apply withOtel to the merged config: withOtel(mergeConfig(getDefaultConfig(__dirname), config))',
);
});
44 changes: 44 additions & 0 deletions metro/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const PACKAGE = 'react-native-open-telemetry';

/**
* Metro helper: runs the SDK's setup (context patch) before the app.
* Appending to `getModulesRunBeforeMainModule` puts it after RN's InitializeCore and before any app module.
* Metro only runs such an entry if it is already in the bundle graph; `src/index.ts` imports `./setup` for that.
* The package is also excluded from inline requires (`nonInlinedRequires`): an inlined import whose only use is
* platform-dead code (e.g. inside `Platform.OS === 'android'` on iOS) would otherwise drop the package, and setup,
* from a release graph.
*/
function withOtel(config, {setupPath = require.resolve('react-native-open-telemetry/setup')} = {}) {
const serializer = config.serializer ?? {};
const original = serializer.getModulesRunBeforeMainModule;
// without it Metro would run only our setup before the app, and drop RN's InitializeCore
if (typeof original !== 'function') {
throw new Error(
`${PACKAGE}/metro: apply withOtel to the merged config: withOtel(mergeConfig(getDefaultConfig(__dirname), config))`,
);
}
if (original.__withOtel) return config;
const wrapped = entry => {
const list = original(entry);
return list.includes(setupPath) ? list : [...list, setupPath];
};
wrapped.__withOtel = true;

const transformer = config.transformer ?? {};
const getTransformOptions = transformer.getTransformOptions ?? (async () => ({}));
const transformOptions = async (...args) => {
const opts = (await getTransformOptions(...args)) ?? {};
const keep = opts.transform?.nonInlinedRequires ?? [];
return {
...opts,
transform: {...opts.transform, nonInlinedRequires: keep.includes(PACKAGE) ? keep : [...keep, PACKAGE]},
};
};
return {
...config,
serializer: {...serializer, getModulesRunBeforeMainModule: wrapped},
transformer: {...transformer, getTransformOptions: transformOptions},
};
}

module.exports = {withOtel};
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"default": "./lib/module/index.js"
},
"./metro": "./metro/index.js",
"./vite": "./vite/index.ts",
"./setup": "./lib/module/setup.js",
"./package.json": "./package.json"
},
Expand All @@ -44,7 +43,6 @@
"ReactNativeOpenTelemetry.podspec",
"nitro.json",
"metro",
"vite",
"!ios/build",
"!android/build",
"!android/gradle",
Expand Down
12 changes: 12 additions & 0 deletions src/context/RNContextManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type {Context} from '@opentelemetry/api';
import {StackContextManager} from '@opentelemetry/sdk-trace';

/** StackContextManager plus a raw enter/leave primitive for the patch wrappers (§6.1). */
export class RNContextManager extends StackContextManager {
/** Makes `ctx` active and returns the previous context; the caller restores it with another swap. */
swap(ctx: Context): Context {
const prev = this._currentContext;
this._currentContext = ctx;
return prev;
}
}
51 changes: 51 additions & 0 deletions src/context/__tests__/patch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {ROOT_CONTEXT, createContextKey} from '@opentelemetry/api';
import {RNContextManager} from '../RNContextManager';
import {installContextPatch} from '../patch';

// Spy installed before the patch: it stands in for the original `then` and records what reaches it.
const realThen = Promise.prototype.then;
const seen: unknown[] = [];
Promise.prototype.then = function (this: Promise<unknown>, ok?: any, err?: any) {
seen.push(ok);
return realThen.call(this, ok, err);
} as typeof realThen;
const spy = Promise.prototype.then;

const cm = new RNContextManager().enable();
installContextPatch(cm);
const patched = {then: Promise.prototype.then, setTimeout: globalThis.setTimeout};

test('installContextPatch twice wraps once', () => {
installContextPatch(new RNContextManager().enable());
expect(Promise.prototype.then).toBe(patched.then);
expect(globalThis.setTimeout).toBe(patched.setTimeout);
expect((globalThis as any)[Symbol.for('com.callstack.otel.patched')]).toMatchObject({then: spy, contextManager: cm});
});

test('then registered at ROOT is not wrapped', () => {
const cb = () => {};
seen.length = 0;
Promise.resolve().then(cb);
expect(cm.active()).toBe(ROOT_CONTEXT);
expect(seen).toEqual([cb]);
const ctx = ROOT_CONTEXT.setValue(createContextKey('k'), 1);
cm.with(ctx, () => Promise.resolve().then(cb));
expect(seen[1]).not.toBe(cb);
});

test('timers forward extra arguments and restore the context', async () => {
const ctx = ROOT_CONTEXT.setValue(createContextKey('k'), 1);
const got = await new Promise<unknown[]>(r => cm.with(ctx, () => setTimeout((a, b) => r([a, b, cm.active()]), 0, 'a', 'b')));
expect(got).toEqual(['a', 'b', ctx]);
expect(cm.active()).toBe(ROOT_CONTEXT);
});

test('setInterval ticks run at ROOT', async () => {
const ctx = ROOT_CONTEXT.setValue(createContextKey('k'), 1);
const got = await new Promise(r =>
cm.with(ctx, () => {
const id = setInterval(() => (clearInterval(id), r(cm.active())), 0);
}),
);
expect(got).toBe(ROOT_CONTEXT);
});
19 changes: 19 additions & 0 deletions src/context/__tests__/probe.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {context} from '@opentelemetry/api';
import {DEGRADED_ATTR, probeAsyncContext, scopeAttributes} from '../probe';
import '../../setup';

// Built with `new Function` so it stays native async whichever Babel config compiled this file.
const nativeStep = new Function('context', 'return (async () => { await null; return context.active(); })')(context);

test('probe resolves true when then is patched and false when async is native', async () => {
const err = jest.spyOn(console, 'error').mockImplementation(() => {});
// a `.then` chain goes through the patched Promise.prototype.then
expect(await probeAsyncContext(() => Promise.resolve().then(() => context.active()))).toBe(true);
expect(scopeAttributes()).toEqual({});
expect(err).not.toHaveBeenCalled();

expect(await probeAsyncContext(nativeStep)).toBe(false);
expect(err).toHaveBeenCalledTimes(1);
expect(String(err.mock.calls[0]?.[0])).toMatch(/await/);
expect(scopeAttributes()).toEqual({[DEGRADED_ATTR]: true});
});
8 changes: 8 additions & 0 deletions src/context/__tests__/scope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type {Tracer} from '@opentelemetry/api';
import {stampScope} from '../scope';

test('stampScope returns a tracer without instrumentationScope unchanged', () => {
const tracer = {startSpan: () => undefined} as unknown as Tracer;
expect(stampScope(tracer, {a: 1})).toBe(tracer);
expect(tracer).not.toHaveProperty('instrumentationScope');
});
74 changes: 74 additions & 0 deletions src/context/patch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import {ROOT_CONTEXT, type Context} from '@opentelemetry/api';
import type {RNContextManager} from './RNContextManager';

export const MARKER = Symbol.for('com.callstack.otel.patched');
const TIMERS = ['setTimeout', 'setImmediate', 'queueMicrotask', 'requestAnimationFrame'] as const;
type Fn = (...args: any[]) => any;

/** Holds the pre-patch functions and the singleton, so a second install (fast refresh, a second SDK copy) is a no-op. */
export type PatchMarker = {
then: typeof Promise.prototype.then;
setInterval: Fn;
contextManager: RNContextManager;
} & Partial<Record<(typeof TIMERS)[number], Fn>>;

/**
* Carries the active context from where a callback is scheduled to where it runs (§6.1).
* At ROOT the original is called unwrapped (every wrapper restores in `finally`, so jobs start at ROOT).
* `setInterval` ticks run in ROOT_CONTEXT (§6.2).
*/
export function installContextPatch(cm: RNContextManager): void {
const g = globalThis as any;
if (g[MARKER]) return;
const marker: PatchMarker = {then: Promise.prototype.then, setInterval: g.setInterval, contextManager: cm};

// fixed arity: `then` callbacks take one argument
const wrap = (ctx: Context, fn: Fn) =>
function (this: unknown, v: unknown) {
const prev = cm.swap(ctx);
try {
return fn.call(this, v);
} finally {
cm.swap(prev);
}
};
// timers forward extra arguments
const wrapArgs = (ctx: Context, fn: Fn) =>
function (this: unknown, ...args: unknown[]) {
const prev = cm.swap(ctx);
try {
return fn.apply(this, args);
} finally {
cm.swap(prev);
}
};

const then = marker.then;
Promise.prototype.then = function (this: Promise<unknown>, ok?: any, err?: any) {
const ctx = cm.active();
if (ctx === ROOT_CONTEXT) return then.call(this, ok, err);
return then.call(
this,
typeof ok === 'function' ? wrap(ctx, ok) : ok,
typeof err === 'function' ? wrap(ctx, err) : err,
);
} as typeof then;

for (const name of TIMERS) {
const orig: Fn | undefined = g[name];
if (typeof orig !== 'function') continue; // rAF is absent in Node, setImmediate on web
marker[name] = orig;
g[name] = function (cb: unknown, ...rest: unknown[]) {
const ctx = cm.active();
return orig(ctx === ROOT_CONTEXT || typeof cb !== 'function' ? cb : wrapArgs(ctx, cb as Fn), ...rest);
};
}

const setInterval = marker.setInterval;
g.setInterval = function (cb: unknown, ...rest: unknown[]) {
const root = cm.active() === ROOT_CONTEXT || typeof cb !== 'function';
return setInterval(root ? cb : wrapArgs(ROOT_CONTEXT, cb as Fn), ...rest);
};

g[MARKER] = marker;
}
28 changes: 28 additions & 0 deletions src/context/probe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {context, createContextKey, type Context} from '@opentelemetry/api';
import {DEGRADED_ATTR, markDegraded} from './scope';

export {DEGRADED_ATTR, scopeAttributes} from './scope';

const KEY = createContextKey('com.callstack.probe');

// `await` here only keeps the context if the bundler downleveled async to generators (then the patched `then` runs).
const defaultStep = async (): Promise<Context> => {
await null;
return context.active();
};

/**
* Startup probe (§6.1.4): does the active context survive `await`? On failure, logs once and flags the SDK's tracers
* as degraded. `step` is injectable for tests.
*/
export async function probeAsyncContext(step: () => Promise<Context> = defaultStep): Promise<boolean> {
const after = await context.with(context.active().setValue(KEY, true), step);
const ok = after.getValue(KEY) === true;
if (!ok && markDegraded()) {
console.error(
`[react-native-open-telemetry] context did not survive \`await\`: native async/await was not downleveled, ` +
`so spans after \`await\` will be roots (${DEGRADED_ATTR}=true). Use the Metro helper (withOtel) or transform async-to-generator.`,
);
}
return ok;
}
32 changes: 32 additions & 0 deletions src/context/scope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type {Attributes, Tracer} from '@opentelemetry/api';

export const DEGRADED_ATTR = 'com.callstack.context.degraded';

let degraded = false;
// ponytail: one entry per tracer; tracers are few and long-lived
const stamped = new Map<{attributes?: Attributes}, Attributes>();

/** Scope attributes every SDK tracer carries: the degraded flag once the startup probe has failed (§6.1.4). */
export const scopeAttributes = (): Attributes => (degraded ? {[DEGRADED_ATTR]: true} : {});

/** Called by the probe on failure; tracers stamped earlier get the flag too. */
export function markDegraded(): boolean {
if (degraded) return false;
degraded = true;
for (const [scope, extra] of stamped) scope.attributes = {...extra, ...scopeAttributes()};
return true;
}

/**
* sdk-trace 3.1 has no API for scope attributes, but its OTLP exporter and our seam read them off
* `tracer.instrumentationScope` at runtime. Every tracer the SDK hands out goes through here (mobile and web).
*/
export function stampScope<T extends Tracer>(tracer: T, extra: Attributes = {}): T {
const scope = (tracer as unknown as {instrumentationScope?: {attributes?: Attributes}}).instrumentationScope;
// an upstream change or a foreign tracer: no scope attributes, but never throw into the app
if (typeof scope !== 'object' || scope === null) return tracer;
const merged = {...stamped.get(scope), ...extra};
stamped.set(scope, merged);
scope.attributes = {...merged, ...scopeAttributes()};
return tracer;
}
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
// Side effect: keeps ./setup in the bundle graph so Metro's runBeforeMainModule entry can run it.
import './setup';

export {};
13 changes: 13 additions & 0 deletions src/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {context} from '@opentelemetry/api';
import {RNContextManager} from './context/RNContextManager';
import {MARKER, installContextPatch, type PatchMarker} from './context/patch';

// Runs before the app (the Metro helper). Reuse the marker's singleton so a re-evaluation (fast refresh,
// a second copy of the SDK) never makes a second context manager.
const existing: PatchMarker | undefined = (globalThis as any)[MARKER];
export const contextManager: RNContextManager = existing?.contextManager ?? new RNContextManager().enable();
installContextPatch(contextManager);
// On a re-evaluation our own manager is already registered; only a foreign one is an error.
if (!context.setGlobalContextManager(contextManager) && !existing) {
console.error('[react-native-open-telemetry] another context manager is already registered; spans may not nest.');
}
2 changes: 1 addition & 1 deletion verify/stages/fast-js.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const stage: Stage = {
order: 20,
e2e: false,
run({sh}) {
sh(['bun', 'run', 'test', '--selectProjects', 'scenarios', '--verbose', '--reporters=default']);
sh(['bun', 'run', 'test', '--selectProjects', 'unit', 'scenarios', '--verbose', '--reporters=default']);
},
};

Expand Down
Loading