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
2 changes: 0 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ jobs:
distribution: temurin
java-version: '17'
- run: bun install --frozen-lockfile
- run: bun install --frozen-lockfile
working-directory: example # static's bundle-size check bundles the example app
- run: bun run prepare
- run: bun verify static fast-js
- uses: actions/upload-artifact@v4
Expand Down
183 changes: 103 additions & 80 deletions bun.lock

Large diffs are not rendered by default.

14 changes: 11 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,18 @@
"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",
"./setup": "./lib/module/setup.js",
"./setup": {
"types": "./lib/typescript/src/setup.d.ts",
"default": "./lib/module/setup.js"
},
"./package.json": "./package.json"
},
"files": [
Expand Down Expand Up @@ -71,18 +78,19 @@
"@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",
Expand Down
2 changes: 1 addition & 1 deletion src/handoff/toSeamSpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const seamValue = (v: unknown): v is AttrValue =>
(Array.isArray(v) && v.every(x => PRIMS.includes(typeof x) && typeof x === typeof v[0]));

// Insertion order; anything the seam cannot carry (null, undefined, objects, bytes, mixed arrays) is dropped.
const attrs = (a: Attributes | undefined): SeamAttribute[] => {
export const attrs = (a: Attributes | undefined): SeamAttribute[] => {
const out: SeamAttribute[] = [];
for (const key in a) {
const value: unknown = a[key];
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Side effect: keeps ./setup in the bundle graph so Metro's runBeforeMainModule entry can run it.
import './setup';

export {};
export {startReactNativeSdk} from './sdk/start';
export type {SdkConfig, SdkHandle} from './sdk/config';
5 changes: 5 additions & 0 deletions src/index.web.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Side effect: registers the context manager and patch before the app runs.
import './setup';

export {startReactNativeSdk} from './sdk/start.web';
export type {SdkConfig, SdkHandle} from './sdk/config';
11 changes: 9 additions & 2 deletions src/internal/testMode.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import type {IdGenerator} from '@opentelemetry/sdk-trace';

export const isTestModeBuild = (): boolean =>
typeof process !== 'undefined' && process.env?.OTEL_TEST_MODE === '1';
// The plain `process.env.OTEL_TEST_MODE` form is what a Babel plugin inlines at bundle time; a browser bundle without
// it has no `process`, hence the catch.
export const isTestModeBuild = (): boolean => {
try {
return process.env.OTEL_TEST_MODE === '1';
} catch {
return false;
}
};

const hex = (prefix: string, n: number, len: number) => prefix + String(n).padStart(len - prefix.length, '0');

Expand Down
8 changes: 2 additions & 6 deletions src/native/otel.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import {NitroModules} from 'react-native-nitro-modules';
import type {Otel} from './Otel.nitro';

/** undefined when the HybridObject isn't registered (web, Jest, Expo Go). */
/** undefined when the HybridObject isn't registered (web, Jest, Expo Go); a constructor failure throws. */
export function getOtel(): Otel | undefined {
try {
return NitroModules.hasHybridObject('Otel') ? NitroModules.createHybridObject<Otel>('Otel') : undefined;
} catch {
return undefined;
}
return NitroModules.hasHybridObject('Otel') ? NitroModules.createHybridObject<Otel>('Otel') : undefined;
}
165 changes: 165 additions & 0 deletions src/sdk/__tests__/start.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import {trace, type ProxyTracerProvider} from '@opentelemetry/api';
import {InMemorySpanExporter, SimpleSpanProcessor} from '@opentelemetry/sdk-trace';
import type {Otel, SeamConfig, SeamSpan} from '../../native/Otel.nitro';
import {MARKER} from '../../context/patch';
import {DEGRADED_ATTR, markDegraded} from '../../context/scope';
import {getOtel} from '../../native/otel';
import {startReactNativeSdk} from '../start';

jest.mock('../../native/otel', () => ({getOtel: jest.fn()}));

const CONFIG = {serviceName: 'shop', exportConfig: {url: 'https://collector.example.com:4318/v1/traces'}};

function fakeOtel({initialized = false, testMode = false, error}: {initialized?: boolean; testMode?: boolean; error?: string} = {}) {
const calls: (SeamConfig | undefined)[] = [];
const spans: SeamSpan[] = [];
const otel = {
initialize(cfg?: SeamConfig) {
calls.push(cfg);
if (error) return {alreadyInitialized: initialized, testMode, error};
if (initialized) return {alreadyInitialized: true, testMode};
if (!cfg) return {alreadyInitialized: false, testMode, error: 'no config'};
initialized = true;
return {alreadyInitialized: false, testMode};
},
handOff: (s: SeamSpan[]) => spans.push(...s),
flush: async () => {},
} as unknown as Otel;
jest.mocked(getOtel).mockReturnValue(otel);
return {calls, spans};
}

let err: jest.SpyInstance;
let warn: jest.SpyInstance;
beforeEach(() => {
const marker = (globalThis as any)[MARKER];
delete marker.handle;
delete marker.warned;
trace.disable();
jest.mocked(getOtel).mockReset();
err = jest.spyOn(console, 'error').mockImplementation(() => {});
warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => jest.restoreAllMocks());

const isNoop = (h: ReturnType<typeof startReactNativeSdk>) =>
!h.tracerProvider.getTracer('t').startSpan('s').isRecording();

test('attaches when native is initialized', () => {
const {calls, spans} = fakeOtel({initialized: true});
const h = startReactNativeSdk(CONFIG);
expect(calls).toHaveLength(1);
expect(warn).toHaveBeenCalledTimes(1); // exportConfig ignored
h.tracerProvider.getTracer('t').startSpan('s').end();
expect(spans.map(s => s.name)).toEqual(['s']);
expect(err).not.toHaveBeenCalled();
});

test('initializes native when it is not', () => {
const {calls, spans} = fakeOtel();
const h = startReactNativeSdk({
serviceName: 'shop',
serviceVersion: '1.2.3',
resourceAttributes: {'deployment.environment.name': 'prod', n: 3, dropped: [1, 'x'] as any},
exportConfig: {url: 'https://collector.example.com:4318/v1/traces', headers: {'x-api-key': 'k'}},
});
expect(calls).toEqual([
{
serviceName: 'shop',
serviceVersion: '1.2.3',
resourceAttributes: [
{key: 'deployment.environment.name', value: 'prod'},
{key: 'n', value: 3},
],
exportUrl: 'https://collector.example.com:4318/v1/traces',
exportHeaders: [{key: 'x-api-key', value: 'k'}],
},
]);
expect(warn).not.toHaveBeenCalled();
h.tracerProvider.getTracer('t').startSpan('s').end();
expect(spans).toHaveLength(1);
});

test('no native module returns a no-op handle and logs once', async () => {
jest.mocked(getOtel).mockReturnValue(undefined);
const h = startReactNativeSdk(CONFIG);
expect(err).toHaveBeenCalledTimes(1);
expect(isNoop(h)).toBe(true);
await h.forceFlush();
await h.shutdown();
expect(startReactNativeSdk(CONFIG)).toBe(h);
expect(err).toHaveBeenCalledTimes(1);
});

test('init error returns a no-op handle and logs once', () => {
fakeOtel({error: 'invalid exportUrl'});
const h = startReactNativeSdk(CONFIG);
expect(err).toHaveBeenCalledTimes(1);
expect(String(err.mock.calls[0])).toMatch(/invalid exportUrl/);
expect(isNoop(h)).toBe(true);
});

test('a partial config names the missing fields, not native\'s "no config"', () => {
const {calls} = fakeOtel();
expect(isNoop(startReactNativeSdk({serviceName: 'shop'}))).toBe(true);
expect(calls).toEqual([undefined]);
expect(err).toHaveBeenCalledTimes(1);
expect(String(err.mock.calls[0])).toMatch(/serviceName and exportConfig\.url are required/);
});

test('a failed native-first init (sticky, R16) was reported by native: no second report', () => {
fakeOtel({initialized: true, error: 'invalid exportUrl'});
const h = startReactNativeSdk();
expect(err).not.toHaveBeenCalled();
expect(isNoop(h)).toBe(true);
});

test('never throws on missing config', () => {
fakeOtel();
expect(isNoop(startReactNativeSdk())).toBe(true);
expect(err).toHaveBeenCalledTimes(1);

delete (globalThis as any)[MARKER].handle;
jest.mocked(getOtel).mockImplementation(() => {
throw new Error('HybridObject constructor failed');
});
expect(isNoop(startReactNativeSdk(CONFIG))).toBe(true);
expect(err).toHaveBeenCalledTimes(2);
});

test('second call returns the first handle with one warning', () => {
fakeOtel({initialized: true});
const h = startReactNativeSdk();
expect(startReactNativeSdk()).toBe(h);
expect(startReactNativeSdk()).toBe(h);
expect(warn).toHaveBeenCalledTimes(1);
// a fast-refresh re-evaluation of the SDK module still returns it
jest.isolateModules(() => expect(require('../start').startReactNativeSdk()).toBe(h));
});

test('user span processors still see spans', () => {
const {spans} = fakeOtel({initialized: true});
const exporter = new InMemorySpanExporter();
const h = startReactNativeSdk({spanProcessors: [new SimpleSpanProcessor({exporter})]});
h.tracerProvider.getTracer('t').startSpan('s').end();
expect(exporter.getFinishedSpans().map(s => s.name)).toEqual(['s']);
expect(spans).toHaveLength(1);
});

test('test-mode native gives 0a ids', () => {
fakeOtel({initialized: true, testMode: true});
const span = startReactNativeSdk().tracerProvider.getTracer('t').startSpan('s');
expect(span.spanContext().traceId).toBe('0a' + '1'.padStart(30, '0'));
expect(span.spanContext().spanId).toBe('0a' + '1'.padStart(14, '0'));
});

test('global provider is the returned provider, its tracers carry the degraded flag', () => {
fakeOtel({initialized: true});
const h = startReactNativeSdk();
expect((trace.getTracerProvider() as ProxyTracerProvider).getDelegate()).toBe(h.tracerProvider);
const scope = (h.tracerProvider.getTracer('t') as any).instrumentationScope;
expect(scope.attributes ?? {}).toEqual({});
markDegraded();
expect(scope.attributes).toEqual({[DEGRADED_ATTR]: true});
expect((trace.getTracer('later') as any).instrumentationScope.attributes).toEqual({[DEGRADED_ATTR]: true});
});
110 changes: 110 additions & 0 deletions src/sdk/__tests__/start.web.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* @jest-environment jsdom
*/
import {context, ROOT_CONTEXT, trace, type ProxyTracerProvider} from '@opentelemetry/api';
import {InMemorySpanExporter, SimpleSpanProcessor} from '@opentelemetry/sdk-trace';
import {MARKER} from '../../context/patch';
import {contextManager} from '../../setup';
import pkg from '../../../package.json';
import {startReactNativeSdk} from '../start.web';

const CONFIG = {serviceName: 'shop', exportConfig: {url: 'https://c.example.com:4318/v1/traces', headers: {'x-api-key': 'k'}}};

// jsdom lacks TextEncoder (every browser has it); the proto serializer needs it.
(globalThis as any).TextEncoder ??= require('util').TextEncoder;

// Jest 30 always adds the `node` condition to require(); load the exporter's browser (fetch) build as a web bundler would.
jest.mock('@opentelemetry/exporter-trace-otlp-proto', () =>
jest.requireActual(require.resolve('@opentelemetry/exporter-trace-otlp-proto').replace(/index\.cjs$/, 'platform/browser/index.cjs')),
);

let err: jest.SpyInstance;
let warn: jest.SpyInstance;
let fetchMock: jest.Mock;
beforeEach(() => {
const marker = (globalThis as any)[MARKER];
delete marker.handle;
delete marker.warned;
trace.disable();
delete process.env.OTEL_TEST_MODE;
fetchMock = jest.fn(async () => ({ok: true, status: 200, headers: {get: () => null}, text: async () => ''}));
(globalThis as any).fetch = fetchMock;
err = jest.spyOn(console, 'error').mockImplementation(() => {});
warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => jest.restoreAllMocks());

const isNoop = (h: ReturnType<typeof startReactNativeSdk>) =>
!h.tracerProvider.getTracer('t').startSpan('s').isRecording();

test('our context manager is the global one after start', () => {
startReactNativeSdk(CONFIG);
const ctx = ROOT_CONTEXT.setValue(Symbol('k'), 1);
expect(context.with(ctx, () => contextManager.active())).toBe(ctx);
expect(err).not.toHaveBeenCalled();
});

test('exports to the url as given, with the headers', async () => {
const h = startReactNativeSdk(CONFIG);
h.tracerProvider.getTracer('t').startSpan('s').end();
await h.forceFlush();
expect(fetchMock).toHaveBeenCalledTimes(1);
const [sent, init] = fetchMock.mock.calls[0];
expect(sent).toBe(CONFIG.exportConfig.url);
expect(init.headers).toMatchObject({'x-api-key': 'k', 'Content-Type': 'application/x-protobuf'});
await h.shutdown();
});

test('missing exportConfig returns a no-op handle', () => {
const h = startReactNativeSdk({serviceName: 'shop'});
expect(isNoop(h)).toBe(true);
expect(err).toHaveBeenCalledTimes(1);
expect(startReactNativeSdk({serviceName: 'shop'})).toBe(h);
expect(err).toHaveBeenCalledTimes(1);
});

test.each(['not a url', 'ftp://c.example.com', 'collector:4318'])('invalid url %s: one error and a no-op handle', url => {
const h = startReactNativeSdk({...CONFIG, exportConfig: {url}});
expect(isNoop(h)).toBe(true);
expect(err).toHaveBeenCalledTimes(1);
expect(String(err.mock.calls[0])).toMatch(/invalid exportConfig\.url/);
expect(fetchMock).not.toHaveBeenCalled();
});

test('second call returns the first handle with one warning', () => {
const h = startReactNativeSdk(CONFIG);
expect(startReactNativeSdk(CONFIG)).toBe(h);
expect(startReactNativeSdk(CONFIG)).toBe(h);
expect(warn).toHaveBeenCalledTimes(1);
});

test('resource, user processors and the global provider', () => {
const exporter = new InMemorySpanExporter();
const h = startReactNativeSdk({
...CONFIG,
serviceVersion: '1.2.3',
resourceAttributes: {'deployment.environment.name': 'prod'},
spanProcessors: [new SimpleSpanProcessor({exporter})],
});
expect((trace.getTracerProvider() as ProxyTracerProvider).getDelegate()).toBe(h.tracerProvider);
trace.getTracer('t').startSpan('s').end();
const span = exporter.getFinishedSpans()[0]!;
expect(span.resource.attributes).toEqual({
'deployment.environment.name': 'prod',
'service.name': 'shop',
'service.version': '1.2.3',
'telemetry.distro.name': 'react-native-open-telemetry',
'telemetry.distro.version': pkg.version,
});
});

test('test mode: 0a ids and no distro attributes', () => {
process.env.OTEL_TEST_MODE = '1';
const exporter = new InMemorySpanExporter();
const h = startReactNativeSdk({...CONFIG, spanProcessors: [new SimpleSpanProcessor({exporter})]});
h.tracerProvider.getTracer('t').startSpan('s').end();
const span = exporter.getFinishedSpans()[0]!;
expect(span.spanContext().traceId).toBe('0a' + '1'.padStart(30, '0'));
expect(span.spanContext().spanId).toBe('0a' + '1'.padStart(14, '0'));
expect(span.resource.attributes).toEqual({'service.name': 'shop'});
});
17 changes: 17 additions & 0 deletions src/sdk/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type {Attributes, TracerProvider} from '@opentelemetry/api';
import type {SpanProcessor} from '@opentelemetry/sdk-trace';

export interface SdkConfig {
serviceName?: string;
serviceVersion?: string;
resourceAttributes?: Attributes;
/** `url` is the OTLP/HTTP traces endpoint, used as given (e.g. `https://collector:4318/v1/traces`, §4.4). */
exportConfig?: {url: string; headers?: Record<string, string>};
Comment thread
adhorodyski marked this conversation as resolved.
Resolved
spanProcessors?: SpanProcessor[];
}

export interface SdkHandle {
tracerProvider: TracerProvider;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
}
Loading