Skip to content
Draft
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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,8 @@ android/generated
.superpowers/
verify/artifacts/
verify/e2e/.e2e/

# SwiftPM (Package.swift: ios/Core tests)
.build/
.swiftpm/
/Package.resolved
324 changes: 234 additions & 90 deletions bun.lock

Large diffs are not rendered by default.

12 changes: 11 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,17 @@ 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>/vite/__tests__/**/*.test.[jt]s',
],
},
'<rootDir>/verify/jest/jest.scenarios.config.js',
// fixtures, degraded projects live under verify/jest/ (later tasks)
'<rootDir>/verify/jest/jest.degraded.config.js',
],
};
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};
22 changes: 17 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,22 @@
"module": "./lib/module/index.js",
"exports": {
".": {
"browser": {
"types": "./lib/typescript/src/index.web.d.ts",
"default": "./lib/module/index.web.js"
},
"types": "./lib/typescript/src/index.d.ts",
"default": "./lib/module/index.js"
},
"./metro": "./metro/index.js",
"./vite": "./vite/index.ts",
"./setup": "./lib/module/setup.js",
"./vite": {
"types": "./vite/index.d.ts",
"default": "./vite/index.js"
},
"./setup": {
"types": "./lib/typescript/src/setup.d.ts",
"default": "./lib/module/setup.js"
},
"./package.json": "./package.json"
},
"files": [
Expand Down Expand Up @@ -73,24 +83,26 @@
"@opentelemetry/core": "~3.1.1",
"@opentelemetry/resources": "~3.1.1",
"@opentelemetry/semantic-conventions": "^1.45.0",
"@opentelemetry/browser-sdk": "0.9.1"
"@opentelemetry/exporter-trace-otlp-proto": "0.301.2"
},
"devDependencies": {
"@changesets/cli": "^2.28.1",
"@e2e-dev/mobile": "0.12.8",
"@opentelemetry/exporter-trace-otlp-proto": "~0.301.2",
"@e2e-dev/web": "0.16.1",
"@react-native/babel-preset": "^0.88.1",
"@types/jest": "^30.0.0",
"@types/node": "^24.0.0",
"babel-jest": "^30.5.2",
"e2e": "0.24.0",
"jest": "^30.5.2",
"jest-environment-jsdom": "30.5.2",
"nitrogen": "0.37.2",
"oxlint": "^1.95.0",
"protobufjs": "^8.8.1",
"react-native-builder-bob": "^0.40.6",
"react-native-nitro-modules": "~0.37.0",
"typescript": "^5.8.3"
"typescript": "^5.8.3",
"vite": "7.3.8"
},
"peerDependencies": {
"react-native": ">=0.79",
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/Vite helper or transform async-to-generator.`,
);
}
return ok;
}
Loading