Repository navigation
v0 [2/7]: startReactNativeSdk on mobile and web #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+592
−182
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'}); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>}; | ||
| spanProcessors?: SpanProcessor[]; | ||
| } | ||
|
|
||
| export interface SdkHandle { | ||
| tracerProvider: TracerProvider; | ||
| forceFlush(): Promise<void>; | ||
| shutdown(): Promise<void>; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.