diff --git a/.gitignore b/.gitignore index b309489..062a0fc 100644 --- a/.gitignore +++ b/.gitignore @@ -78,7 +78,7 @@ android/keystores/debug.keystore # generated by bob lib/ -# Vite +# web builds (expo export) dist/ # React Native Codegen @@ -89,3 +89,8 @@ android/generated .superpowers/ verify/artifacts/ verify/e2e/.e2e/ + +# SwiftPM (Package.swift: ios/Core tests) +.build/ +.swiftpm/ +/Package.resolved diff --git a/jest.config.js b/jest.config.js index 2085615..b2017ea 100644 --- a/jest.config.js +++ b/jest.config.js @@ -13,7 +13,16 @@ module.exports = { '/verify/harness/**/*.test.ts', ], }, + { + displayName: 'unit', + testEnvironment: 'node', + transform, + testMatch: [ + '/src/**/__tests__/**/*.test.[jt]s', + '/metro/__tests__/**/*.test.[jt]s', + ], + }, '/verify/jest/jest.scenarios.config.js', - // fixtures, degraded projects live under verify/jest/ (later tasks) + // the degraded project lives under verify/jest/ (later task) ], }; diff --git a/metro/__tests__/withOtel.test.js b/metro/__tests__/withOtel.test.js new file mode 100644 index 0000000..76780c0 --- /dev/null +++ b/metro/__tests__/withOtel.test.js @@ -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))', + ); +}); diff --git a/metro/index.js b/metro/index.js new file mode 100644 index 0000000..0f4ef4e --- /dev/null +++ b/metro/index.js @@ -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}; diff --git a/package.json b/package.json index 8dd37d0..528a62c 100644 --- a/package.json +++ b/package.json @@ -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" }, @@ -44,7 +43,6 @@ "ReactNativeOpenTelemetry.podspec", "nitro.json", "metro", - "vite", "!ios/build", "!android/build", "!android/gradle", diff --git a/src/context/RNContextManager.ts b/src/context/RNContextManager.ts new file mode 100644 index 0000000..66f2257 --- /dev/null +++ b/src/context/RNContextManager.ts @@ -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; + } +} diff --git a/src/context/__tests__/patch.test.ts b/src/context/__tests__/patch.test.ts new file mode 100644 index 0000000..16991a4 --- /dev/null +++ b/src/context/__tests__/patch.test.ts @@ -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, 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(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); +}); diff --git a/src/context/__tests__/probe.test.ts b/src/context/__tests__/probe.test.ts new file mode 100644 index 0000000..713c005 --- /dev/null +++ b/src/context/__tests__/probe.test.ts @@ -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}); +}); diff --git a/src/context/__tests__/scope.test.ts b/src/context/__tests__/scope.test.ts new file mode 100644 index 0000000..4f10889 --- /dev/null +++ b/src/context/__tests__/scope.test.ts @@ -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'); +}); diff --git a/src/context/patch.ts b/src/context/patch.ts new file mode 100644 index 0000000..9a895b3 --- /dev/null +++ b/src/context/patch.ts @@ -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>; + +/** + * 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, 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; +} diff --git a/src/context/probe.ts b/src/context/probe.ts new file mode 100644 index 0000000..fcb1b31 --- /dev/null +++ b/src/context/probe.ts @@ -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 => { + 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 = defaultStep): Promise { + 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; +} diff --git a/src/context/scope.ts b/src/context/scope.ts new file mode 100644 index 0000000..b9100a2 --- /dev/null +++ b/src/context/scope.ts @@ -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(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; +} diff --git a/src/index.ts b/src/index.ts index cb0ff5c..4d676b0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1 +1,4 @@ +// Side effect: keeps ./setup in the bundle graph so Metro's runBeforeMainModule entry can run it. +import './setup'; + export {}; diff --git a/src/setup.ts b/src/setup.ts new file mode 100644 index 0000000..86fd7b8 --- /dev/null +++ b/src/setup.ts @@ -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.'); +} diff --git a/verify/stages/fast-js.ts b/verify/stages/fast-js.ts index f861d3e..34f1faa 100644 --- a/verify/stages/fast-js.ts +++ b/verify/stages/fast-js.ts @@ -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']); }, }; diff --git a/verify/static/packContents.test.ts b/verify/static/packContents.test.ts index 344eb80..5a5394e 100644 --- a/verify/static/packContents.test.ts +++ b/verify/static/packContents.test.ts @@ -1,6 +1,6 @@ import {packContents} from './packContents'; -const complete = ['package.json', 'lib/module/index.js', 'src/index.ts', 'nitrogen/generated/x.hpp']; +const complete = ['package.json', 'lib/module/index.js', 'src/index.ts', 'nitrogen/generated/x.hpp', 'metro/index.js', 'android/build.gradle', 'ios/Adapter/HybridOtel.swift', 'ReactNativeOpenTelemetry.podspec']; test('reports missing nitrogen/', () => { expect(packContents(complete.filter(p => !p.startsWith('nitrogen/')))).toEqual(['nitrogen/']); diff --git a/verify/static/packContents.ts b/verify/static/packContents.ts index a887ca1..dddbfec 100644 --- a/verify/static/packContents.ts +++ b/verify/static/packContents.ts @@ -1,4 +1,4 @@ -export const REQUIRED = ['package.json', 'lib/', 'src/', 'nitrogen/']; +export const REQUIRED = ['package.json', 'lib/', 'src/', 'nitrogen/', 'metro/', 'android/', 'ios/', 'ReactNativeOpenTelemetry.podspec']; /** Returns the required paths missing from the `npm pack --dry-run --json` file list. */ export function packContents(list: string[], required: string[] = REQUIRED): string[] {