@grafana/faro-react-native-tracing 1.3.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -0
- package/dist/cjs/exporters/faroTraceExporter.js +2 -1
- package/dist/cjs/exporters/faroTraceExporter.js.map +1 -1
- package/dist/cjs/exporters/faroTraceExporter.utils.js +33 -0
- package/dist/cjs/exporters/faroTraceExporter.utils.js.map +1 -1
- package/dist/cjs/instrumentation.js +259 -44
- package/dist/cjs/instrumentation.js.map +1 -1
- package/dist/cjs/instrumentations/getDefaultOTELInstrumentations.js +28 -20
- package/dist/cjs/instrumentations/getDefaultOTELInstrumentations.js.map +1 -1
- package/dist/cjs/instrumentations/instrumentationUtils.js +15 -0
- package/dist/cjs/instrumentations/instrumentationUtils.js.map +1 -1
- package/dist/cjs/processors/httpRequestMonitorSpanProcessor.js +27 -13
- package/dist/cjs/processors/httpRequestMonitorSpanProcessor.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/esm/exporters/faroTraceExporter.js +2 -1
- package/dist/esm/exporters/faroTraceExporter.js.map +1 -1
- package/dist/esm/exporters/faroTraceExporter.utils.js +32 -0
- package/dist/esm/exporters/faroTraceExporter.utils.js.map +1 -1
- package/dist/esm/instrumentation.js +237 -43
- package/dist/esm/instrumentation.js.map +1 -1
- package/dist/esm/instrumentations/getDefaultOTELInstrumentations.js +27 -21
- package/dist/esm/instrumentations/getDefaultOTELInstrumentations.js.map +1 -1
- package/dist/esm/instrumentations/instrumentationUtils.js +14 -0
- package/dist/esm/instrumentations/instrumentationUtils.js.map +1 -1
- package/dist/esm/processors/httpRequestMonitorSpanProcessor.js +27 -13
- package/dist/esm/processors/httpRequestMonitorSpanProcessor.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/types/instrumentation.d.ts +12 -4
- package/dist/types/instrumentations/getDefaultOTELInstrumentations.d.ts +2 -0
- package/dist/types/instrumentations/instrumentationUtils.d.ts +2 -0
- package/dist/types/types.d.ts +4 -0
- package/package.json +13 -13
- package/src/exporters/faroTraceExporter.events.test.ts +90 -0
- package/src/exporters/faroTraceExporter.ts +2 -1
- package/src/exporters/faroTraceExporter.utils.ts +32 -0
- package/src/httpSemantics.test.ts +300 -0
- package/src/instrumentation.test.ts +740 -0
- package/src/instrumentation.ts +299 -67
- package/src/instrumentations/getDefaultOTELInstrumentations.test.ts +28 -1
- package/src/instrumentations/getDefaultOTELInstrumentations.ts +41 -32
- package/src/instrumentations/instrumentationUtils.ts +13 -0
- package/src/processors/httpRequestMonitorSpanProcessor.ts +27 -15
- package/src/types.ts +4 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAAiE;AAEjE,4CAA2G;AAC3G,kEAA0E;AAC1E,sDAAmF;AACnF,gEAAqH;AAErH,8DAAmE;AACnE,4EAI6C;AAE7C,gDAAmG;AAGnG,mEAAkE;AAClE,8EAA2F;AAC3F,oGAAmG;AACnG,gGAA+F;AAC/F,gGAA+F;AAC/F,qCAamB;AAEnB,2CAAsD;AAEtD,qCAAqC;AACrC,gFAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;IAA4C,0CAAmB;IAQ7D,gCAAoB,OAA2C;QAA3C,wBAAA,EAAA,YAA2C;QAC7D,YAAA,MAAK,WAAE,SAAC;QADU,aAAO,GAAP,OAAO,CAAoC;QAP/D,UAAI,GAAG,oCAAoC,CAAC;QAC5C,aAAO,GAAG,mBAAO,CAAC;;IAQlB,CAAC;IAED,2CAAU,GAAV;QAAA,iBAyJC;;QAxJC,IAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC7B,IAAM,UAAU,GAAe,EAAE,CAAC;QAElC,iBAAiB;QACjB,IAA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AAxMD,CAA4C,+BAAmB,GAwM9D;AAxMY,wDAAsB","sourcesContent":["import { context, propagation, trace } from '@opentelemetry/api';\nimport type { Attributes } from '@opentelemetry/api';\nimport { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\nimport { defaultResource, resourceFromAttributes } from '@opentelemetry/resources';\nimport { BatchSpanProcessor, BasicTracerProvider as ReactNativeTracerProvider } from '@opentelemetry/sdk-trace-base';\nimport type { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';\nimport { StackContextManager } from '@opentelemetry/sdk-trace-web';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,\n} from '@opentelemetry/semantic-conventions';\n\nimport { BaseInstrumentation, getInternalFaroFromGlobalObject, VERSION } from '@grafana/faro-core';\nimport type { Transport } from '@grafana/faro-core';\n\nimport { FaroTraceExporter } from './exporters/faroTraceExporter';\nimport { getReactNativeDevServerIgnoreUrls } from './instrumentations/devServerIgnoreUrls';\nimport { getDefaultOTELInstrumentations } from './instrumentations/getDefaultOTELInstrumentations';\nimport { FaroMetaAttributesSpanProcessor } from './processors/faroMetaAttributesSpanProcessor';\nimport { HttpRequestMonitorSpanProcessor } from './processors/httpRequestMonitorSpanProcessor';\nimport {\n ATTR_APP_VERSION,\n ATTR_DEPLOYMENT_ENVIRONMENT_NAME,\n ATTR_DEVICE_BRAND,\n ATTR_DEVICE_LOCALE,\n ATTR_DEVICE_MODEL,\n ATTR_DEVICE_OS_VERSION,\n ATTR_DEVICE_PLATFORM,\n ATTR_PROCESS_RUNTIME_NAME,\n ATTR_PROCESS_RUNTIME_VERSION,\n ATTR_SERVICE_NAMESPACE,\n ATTR_TELEMETRY_DISTRO_NAME,\n ATTR_TELEMETRY_DISTRO_VERSION,\n} from './semconv';\nimport type { TracingInstrumentationOptions } from './types';\nimport { getSamplingDecision } from './utils/sampler';\n\n// Import React Native TracerProvider\n// Note: We use the base provider since React Native doesn't have a specific one\n\n/**\n * TracingInstrumentation for React Native\n *\n * Enables distributed tracing with OpenTelemetry for React Native applications.\n *\n * IMPORTANT: Infinite loop prevention\n * - Uses internalLogger for debugging instead of console\n * - Collector URLs are added to ignoreUrls in HTTP instrumentation\n * - BatchSpanProcessor delays span export to avoid blocking\n * - No console logging during trace export\n *\n * Example usage:\n * ```ts\n * import { initializeFaro } from '@grafana/faro-react-native';\n * import { TracingInstrumentation } from '@grafana/faro-react-native-tracing';\n *\n * initializeFaro({\n * // ... other config\n * instrumentations: [\n * new TracingInstrumentation({\n * propagateTraceHeaderCorsUrls: [/https:\\\\/\\\\/my-api\\\\.com/],\n * }),\n * ],\n * });\n * ```\n */\nexport class TracingInstrumentation extends BaseInstrumentation {\n name = '@grafana/faro-react-native-tracing';\n version = VERSION;\n\n static SCHEDULED_BATCH_DELAY_MS = 1000;\n\n private provider?: BasicTracerProvider;\n\n constructor(private options: TracingInstrumentationOptions = {}) {\n super();\n }\n\n initialize(): void {\n const options = this.options;\n const attributes: Attributes = {};\n\n // App attributes\n if (this.config.app.name) {\n attributes[ATTR_SERVICE_NAME] = this.config.app.name;\n }\n\n if (this.config.app.namespace) {\n attributes[ATTR_SERVICE_NAMESPACE] = this.config.app.namespace;\n }\n\n if (this.config.app.version) {\n attributes[ATTR_SERVICE_VERSION] = this.config.app.version;\n attributes[ATTR_APP_VERSION] = this.config.app.version;\n }\n\n if (this.config.app.environment) {\n attributes[ATTR_DEPLOYMENT_ENVIRONMENT_NAME] = this.config.app.environment;\n\n /**\n * @deprecated will be removed in the future and has been replaced by ATTR_DEPLOYMENT_ENVIRONMENT_NAME (deployment.environment.name)\n * We need to keep this for compatibility with some internal services for now.\n */\n attributes[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT] = this.config.app.environment;\n }\n\n // Device/Platform attributes from React Native\n // Note: metas.value contains all meta providers, we need to check if device meta exists\n const allMetas = this.metas.value as Record<string, unknown>;\n const deviceMeta = allMetas['device'] as\n | {\n model?: string;\n brand?: string;\n osName?: string;\n osVersion?: string;\n locale?: string;\n }\n | undefined;\n\n if (deviceMeta?.model) {\n attributes[ATTR_DEVICE_MODEL] = deviceMeta.model;\n }\n\n if (deviceMeta?.brand) {\n attributes[ATTR_DEVICE_BRAND] = deviceMeta.brand;\n }\n\n if (deviceMeta?.osName) {\n attributes[ATTR_DEVICE_PLATFORM] = deviceMeta.osName;\n }\n\n if (deviceMeta?.osVersion) {\n attributes[ATTR_DEVICE_OS_VERSION] = deviceMeta.osVersion;\n }\n\n if (deviceMeta?.locale) {\n attributes[ATTR_DEVICE_LOCALE] = deviceMeta.locale;\n }\n\n attributes[ATTR_PROCESS_RUNTIME_NAME] = 'react-native';\n attributes[ATTR_PROCESS_RUNTIME_VERSION] = deviceMeta?.osVersion ?? 'unknown';\n\n attributes[ATTR_TELEMETRY_DISTRO_NAME] = 'faro-react-native-sdk';\n attributes[ATTR_TELEMETRY_DISTRO_VERSION] = VERSION;\n\n // Merge with user-provided attributes\n Object.assign(attributes, options.resourceAttributes);\n\n const resource = defaultResource().merge(resourceFromAttributes(attributes));\n\n // Create tracer provider with span processors\n this.provider = new ReactNativeTracerProvider({\n resource,\n sampler: {\n shouldSample: () => {\n return {\n decision: getSamplingDecision(this.api.getSession()),\n };\n },\n },\n spanProcessors: [\n options.spanProcessor ??\n new HttpRequestMonitorSpanProcessor(\n new FaroMetaAttributesSpanProcessor(\n new BatchSpanProcessor(new FaroTraceExporter({ api: this.api }), {\n scheduledDelayMillis: TracingInstrumentation.SCHEDULED_BATCH_DELAY_MS,\n maxExportBatchSize: 30,\n }),\n this.metas\n )\n ),\n ],\n });\n\n // Register the provider as the global tracer provider\n // This is CRITICAL for the tracer to generate real trace IDs instead of all zeros\n trace.setGlobalTracerProvider(this.provider);\n\n // Register a global ContextManager. Without one, OTel falls back to the NoopContextManager,\n // which always returns ROOT_CONTEXT — so when `@opentelemetry/instrumentation-fetch` does\n // `context.with(setSpan(active(), createdSpan), () => _addHeaders(...))` the span set on the\n // wrapped context is invisible inside `_addHeaders` and `propagation.inject` writes nothing.\n // `StackContextManager` is pure JS (no DOM/Zone deps) and works in React Native.\n context.setGlobalContextManager(options.contextManager ?? new StackContextManager().enable());\n\n // Register the global text-map propagator. Without this, OTel falls back to a\n // NoopTextMapPropagator and `propagation.inject(...)` becomes a no-op, meaning\n // `traceparent` / `tracestate` (and `baggage`) headers are never written on the\n // outbound fetch/XHR — so the backend receives no context and starts a new trace.\n propagation.setGlobalPropagator(\n options.propagator ??\n new CompositePropagator({\n propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()],\n })\n );\n\n const {\n enableFetchInstrumentation,\n enableXhrInstrumentation,\n propagateTraceHeaderCorsUrls,\n fetchInstrumentationOptions,\n xhrInstrumentationOptions,\n } = this.options.instrumentationOptions ?? {};\n\n // Get ignore URLs from transports to prevent infinite loops\n const ignoreUrls = this.getIgnoreUrls();\n\n // Register instrumentations\n registerInstrumentations({\n instrumentations:\n options.instrumentations ??\n getDefaultOTELInstrumentations({\n ignoreUrls,\n enableFetchInstrumentation,\n enableXhrInstrumentation,\n propagateTraceHeaderCorsUrls,\n fetchInstrumentationOptions,\n xhrInstrumentationOptions,\n }),\n });\n\n // Expose OTEL API on the global Faro instance for manual span creation\n // This allows users to access trace and context APIs via faro.otel\n const globalFaroInstance = getInternalFaroFromGlobalObject();\n if (globalFaroInstance) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Extending Faro instance with OTEL API\n (globalFaroInstance as any).otel = {\n trace,\n context,\n };\n }\n }\n\n /**\n * Get ignore URLs from all transports to avoid tracing collector requests\n * CRITICAL: This prevents infinite loops where trace exports trigger more traces\n */\n private getIgnoreUrls(): Array<string | RegExp> {\n // Get URLs from transports' getIgnoreUrls() method\n const transportUrls = this.transports.transports.flatMap((transport: Transport) => {\n return transport.getIgnoreUrls();\n });\n\n // Create regex patterns that match both with and without trailing slashes\n // This is critical because fetch() might add trailing slashes\n const regexPatterns = transportUrls.map((url) => {\n if (typeof url === 'string') {\n // Escape special regex characters and make trailing slash optional\n const escapedUrl = url.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`^${escapedUrl}/?$`);\n }\n return url;\n });\n\n // Return dev-server, original transport URLs, and regex patterns for maximum coverage.\n return [...getReactNativeDevServerIgnoreUrls(), ...transportUrls, ...regexPatterns];\n }\n\n /**\n * Shutdown the tracer provider\n */\n async shutdown(): Promise<void> {\n if (this.provider) {\n await this.provider.shutdown();\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAAiE;AAEjE,4CAA2G;AAC3G,kEAA0E;AAE1E,sDAAmF;AACnF,gEAAqH;AAErH,8DAAmE;AACnE,4EAI6C;AAE7C,gDAAmG;AAGnG,mEAAkE;AAClE,8EAA2F;AAC3F,oGAG2D;AAC3D,gGAA+F;AAC/F,gGAA+F;AAC/F,qCAamB;AAEnB,2CAAsD;AAMtD,IAAM,wBAAwB,GAAG,IAAI,OAAO,EAAmB,CAAC;AAEhE;;;;GAIG;AACH;IACE,+BAA6B,SAAwB;QAAxB,cAAS,GAAT,SAAS,CAAe;IAAG,CAAC;IAEzD,0CAAU,GAAV;QACE,OAAO,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,CAAC;IACrC,CAAC;IAED,uCAAO,GAAP,UAAQ,IAAU,EAAE,aAAsB;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;IAC9C,CAAC;IAED,wCAAQ,GAAR,UAAS,IAAU;;QACjB,MAAA,MAAA,IAAI,CAAC,SAAS,EAAC,QAAQ,mDAAG,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,qCAAK,GAAL,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L,CAAC;IAxXM,+CAAwB,GAAG,IAAI,AAAP,CAAQ;IAyXzC,6BAAC;CAAA,AA7XD,CAA4C,+BAAmB,GA6X9D;AA7XY,wDAAsB","sourcesContent":["import { context, propagation, trace } from '@opentelemetry/api';\nimport type { Attributes, Context, ContextManager } from '@opentelemetry/api';\nimport { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\nimport type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { defaultResource, resourceFromAttributes } from '@opentelemetry/resources';\nimport { BatchSpanProcessor, BasicTracerProvider as ReactNativeTracerProvider } from '@opentelemetry/sdk-trace-base';\nimport type { BasicTracerProvider, ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { StackContextManager } from '@opentelemetry/sdk-trace-web';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,\n} from '@opentelemetry/semantic-conventions';\n\nimport { BaseInstrumentation, getInternalFaroFromGlobalObject, VERSION } from '@grafana/faro-core';\nimport type { Faro, OTELApi, Transport } from '@grafana/faro-core';\n\nimport { FaroTraceExporter } from './exporters/faroTraceExporter';\nimport { getReactNativeDevServerIgnoreUrls } from './instrumentations/devServerIgnoreUrls';\nimport {\n getDefaultOTELInstrumentations,\n updateDefaultOTELInstrumentations,\n} from './instrumentations/getDefaultOTELInstrumentations';\nimport { FaroMetaAttributesSpanProcessor } from './processors/faroMetaAttributesSpanProcessor';\nimport { HttpRequestMonitorSpanProcessor } from './processors/httpRequestMonitorSpanProcessor';\nimport {\n ATTR_APP_VERSION,\n ATTR_DEPLOYMENT_ENVIRONMENT_NAME,\n ATTR_DEVICE_BRAND,\n ATTR_DEVICE_LOCALE,\n ATTR_DEVICE_MODEL,\n ATTR_DEVICE_OS_VERSION,\n ATTR_DEVICE_PLATFORM,\n ATTR_PROCESS_RUNTIME_NAME,\n ATTR_PROCESS_RUNTIME_VERSION,\n ATTR_SERVICE_NAMESPACE,\n ATTR_TELEMETRY_DISTRO_NAME,\n ATTR_TELEMETRY_DISTRO_VERSION,\n} from './semconv';\nimport type { TracingInstrumentationOptions } from './types';\nimport { getSamplingDecision } from './utils/sampler';\n\n// Import React Native TracerProvider\n// Note: We use the base provider since React Native doesn't have a specific one\n\ntype FaroWithOtel = Faro & { otel?: unknown };\nconst detachedInstrumentations = new WeakSet<Instrumentation>();\n\n/**\n * Keeps a caller-supplied processor reusable across Faro remove/add cycles.\n * Explicit TracingInstrumentation.shutdown() remains responsible for the\n * processor's terminal shutdown.\n */\nclass BorrowedSpanProcessor implements SpanProcessor {\n constructor(private readonly processor: SpanProcessor) {}\n\n forceFlush(): Promise<void> {\n return this.processor.forceFlush();\n }\n\n onStart(span: Span, parentContext: Context): void {\n this.processor.onStart(span, parentContext);\n }\n\n onEnding(span: Span): void {\n this.processor.onEnding?.(span);\n }\n\n onEnd(span: ReadableSpan): void {\n this.processor.onEnd(span);\n }\n\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n}\n\ninterface TracingRegistration {\n contextManager?: ContextManager;\n faro?: FaroWithOtel;\n faroOtel?: OTELApi;\n instrumentations: Instrumentation[];\n ownsContextManager: boolean;\n ownsContextManagerInstance: boolean;\n ownsPropagator: boolean;\n ownsTracerProvider: boolean;\n previousFaroOtel?: unknown;\n provider: BasicTracerProvider;\n shutdownPromise?: Promise<void>;\n unregisterInstrumentations?: VoidFunction;\n}\n\n/**\n * TracingInstrumentation for React Native\n *\n * Enables distributed tracing with OpenTelemetry for React Native applications.\n *\n * IMPORTANT: Infinite loop prevention\n * - Uses internalLogger for debugging instead of console\n * - Collector URLs are added to ignoreUrls in HTTP instrumentation\n * - BatchSpanProcessor delays span export to avoid blocking\n * - No console logging during trace export\n *\n * Example usage:\n * ```ts\n * import { initializeFaro } from '@grafana/faro-react-native';\n * import { TracingInstrumentation } from '@grafana/faro-react-native-tracing';\n *\n * initializeFaro({\n * // ... other config\n * instrumentations: [\n * new TracingInstrumentation({\n * propagateTraceHeaderCorsUrls: [/https:\\\\/\\\\/my-api\\\\.com/],\n * }),\n * ],\n * });\n * ```\n */\nexport class TracingInstrumentation extends BaseInstrumentation {\n name = '@grafana/faro-react-native-tracing';\n version = VERSION;\n\n static SCHEDULED_BATCH_DELAY_MS = 1000;\n\n private activeRegistration?: TracingRegistration;\n private defaultInstrumentations?: Instrumentation[];\n private pendingShutdowns = new Set<Promise<void>>();\n private suppliedSpanProcessorShutdown?: Promise<void>;\n\n constructor(private options: TracingInstrumentationOptions = {}) {\n super();\n }\n\n initialize(): void {\n this.destroy();\n\n const options = this.options;\n const attributes: Attributes = {};\n\n // App attributes\n if (this.config.app.name) {\n attributes[ATTR_SERVICE_NAME] = this.config.app.name;\n }\n\n if (this.config.app.namespace) {\n attributes[ATTR_SERVICE_NAMESPACE] = this.config.app.namespace;\n }\n\n if (this.config.app.version) {\n attributes[ATTR_SERVICE_VERSION] = this.config.app.version;\n attributes[ATTR_APP_VERSION] = this.config.app.version;\n }\n\n if (this.config.app.environment) {\n attributes[ATTR_DEPLOYMENT_ENVIRONMENT_NAME] = this.config.app.environment;\n\n /**\n * @deprecated will be removed in the future and has been replaced by ATTR_DEPLOYMENT_ENVIRONMENT_NAME (deployment.environment.name)\n * We need to keep this for compatibility with some internal services for now.\n */\n attributes[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT] = this.config.app.environment;\n }\n\n // Device/Platform attributes from React Native\n // Note: metas.value contains all meta providers, we need to check if device meta exists\n const allMetas = this.metas.value as Record<string, unknown>;\n const deviceMeta = allMetas['device'] as\n | {\n model?: string;\n brand?: string;\n osName?: string;\n osVersion?: string;\n locale?: string;\n }\n | undefined;\n\n if (deviceMeta?.model) {\n attributes[ATTR_DEVICE_MODEL] = deviceMeta.model;\n }\n\n if (deviceMeta?.brand) {\n attributes[ATTR_DEVICE_BRAND] = deviceMeta.brand;\n }\n\n if (deviceMeta?.osName) {\n attributes[ATTR_DEVICE_PLATFORM] = deviceMeta.osName;\n }\n\n if (deviceMeta?.osVersion) {\n attributes[ATTR_DEVICE_OS_VERSION] = deviceMeta.osVersion;\n }\n\n if (deviceMeta?.locale) {\n attributes[ATTR_DEVICE_LOCALE] = deviceMeta.locale;\n }\n\n attributes[ATTR_PROCESS_RUNTIME_NAME] = 'react-native';\n attributes[ATTR_PROCESS_RUNTIME_VERSION] = deviceMeta?.osVersion ?? 'unknown';\n\n attributes[ATTR_TELEMETRY_DISTRO_NAME] = 'faro-react-native-sdk';\n attributes[ATTR_TELEMETRY_DISTRO_VERSION] = VERSION;\n\n // Merge with user-provided attributes\n Object.assign(attributes, options.resourceAttributes);\n\n const resource = defaultResource().merge(resourceFromAttributes(attributes));\n\n // Create tracer provider with span processors\n const provider = new ReactNativeTracerProvider({\n resource,\n sampler: {\n shouldSample: () => {\n return {\n decision: getSamplingDecision(this.api.getSession()),\n };\n },\n },\n spanProcessors: [\n (options.spanProcessor && new BorrowedSpanProcessor(options.spanProcessor)) ??\n new HttpRequestMonitorSpanProcessor(\n new FaroMetaAttributesSpanProcessor(\n new BatchSpanProcessor(new FaroTraceExporter({ api: this.api }), {\n scheduledDelayMillis: TracingInstrumentation.SCHEDULED_BATCH_DELAY_MS,\n maxExportBatchSize: 30,\n }),\n this.metas\n )\n ),\n ],\n });\n\n const registration: TracingRegistration = {\n instrumentations: [],\n ownsContextManager: false,\n ownsContextManagerInstance: false,\n ownsPropagator: false,\n ownsTracerProvider: false,\n provider,\n };\n this.activeRegistration = registration;\n\n try {\n // Register the provider as the global tracer provider\n // This is CRITICAL for the tracer to generate real trace IDs instead of all zeros\n if (!trace.setGlobalTracerProvider(provider)) {\n throw new Error(\n 'Unable to register the Faro OpenTelemetry tracer provider. Remove the existing global tracer provider before initializing Faro tracing.'\n );\n }\n registration.ownsTracerProvider = true;\n\n // Register a global ContextManager. Without one, OTel falls back to the NoopContextManager,\n // which always returns ROOT_CONTEXT — so when `@opentelemetry/instrumentation-fetch` does\n // `context.with(setSpan(active(), createdSpan), () => _addHeaders(...))` the span set on the\n // wrapped context is invisible inside `_addHeaders` and `propagation.inject` writes nothing.\n // `StackContextManager` is pure JS (no DOM/Zone deps) and works in React Native.\n const contextManager = (options.contextManager ?? new StackContextManager()).enable();\n registration.contextManager = contextManager;\n registration.ownsContextManagerInstance = options.contextManager == null;\n registration.ownsContextManager = context.setGlobalContextManager(contextManager);\n\n // Register the global text-map propagator. Without this, OTel falls back to a\n // NoopTextMapPropagator and `propagation.inject(...)` becomes a no-op, meaning\n // `traceparent` / `tracestate` (and `baggage`) headers are never written on the\n // outbound fetch/XHR — so the backend receives no context and starts a new trace.\n registration.ownsPropagator = propagation.setGlobalPropagator(\n options.propagator ??\n new CompositePropagator({\n propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()],\n })\n );\n\n const {\n enableFetchInstrumentation,\n enableXhrInstrumentation,\n propagateTraceHeaderCorsUrls,\n fetchInstrumentationOptions,\n xhrInstrumentationOptions,\n } = this.options.instrumentationOptions ?? {};\n\n // Get ignore URLs from transports to prevent infinite loops\n const ignoreUrls = this.getIgnoreUrls();\n\n const defaultInstrumentationOptions = {\n ignoreUrls,\n enableFetchInstrumentation,\n enableXhrInstrumentation,\n propagateTraceHeaderCorsUrls,\n fetchInstrumentationOptions,\n xhrInstrumentationOptions,\n };\n\n if (options.instrumentations) {\n registration.instrumentations = options.instrumentations.flat();\n } else if (this.defaultInstrumentations) {\n updateDefaultOTELInstrumentations(this.defaultInstrumentations, defaultInstrumentationOptions);\n registration.instrumentations = this.defaultInstrumentations;\n } else {\n this.defaultInstrumentations = getDefaultOTELInstrumentations(defaultInstrumentationOptions).flat();\n registration.instrumentations = this.defaultInstrumentations;\n }\n\n const instrumentationsNeedingExplicitEnable = registration.instrumentations.filter(\n (instrumentation) =>\n detachedInstrumentations.has(instrumentation) && instrumentation.getConfig().enabled === true\n );\n registration.unregisterInstrumentations = registerInstrumentations({\n instrumentations: registration.instrumentations,\n });\n registration.instrumentations.forEach((instrumentation) => {\n detachedInstrumentations.delete(instrumentation);\n });\n instrumentationsNeedingExplicitEnable.forEach((instrumentation) => instrumentation.enable());\n\n // Expose OTEL API on the global Faro instance for manual span creation\n // This allows users to access trace and context APIs via faro.otel\n const globalFaroInstance = getInternalFaroFromGlobalObject() as FaroWithOtel | undefined;\n if (globalFaroInstance) {\n const faroOtel: OTELApi = { trace, context };\n registration.faro = globalFaroInstance;\n registration.faroOtel = faroOtel;\n registration.previousFaroOtel = globalFaroInstance.otel;\n globalFaroInstance.otel = faroOtel;\n }\n } catch (error) {\n this.destroy();\n throw error;\n }\n }\n\n /**\n * Get ignore URLs from all transports to avoid tracing collector requests\n * CRITICAL: This prevents infinite loops where trace exports trigger more traces\n */\n private getIgnoreUrls(): Array<string | RegExp> {\n // Get URLs from transports' getIgnoreUrls() method\n const transportUrls = this.transports.transports.flatMap((transport: Transport) => {\n return transport.getIgnoreUrls();\n });\n\n // Create regex patterns that match both with and without trailing slashes\n // This is critical because fetch() might add trailing slashes\n const regexPatterns = transportUrls.map((url) => {\n if (typeof url === 'string') {\n // Escape special regex characters and make trailing slash optional\n const escapedUrl = url.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`^${escapedUrl}/?$`);\n }\n return url;\n });\n\n // Return dev-server, original transport URLs, and regex patterns for maximum coverage.\n return [...getReactNativeDevServerIgnoreUrls(), ...transportUrls, ...regexPatterns];\n }\n\n private detachRegistration(): TracingRegistration | undefined {\n const registration = this.activeRegistration;\n if (!registration) {\n return undefined;\n }\n this.activeRegistration = undefined;\n registration.instrumentations.forEach((instrumentation) => detachedInstrumentations.add(instrumentation));\n\n let unregistered = false;\n if (registration.unregisterInstrumentations) {\n try {\n registration.unregisterInstrumentations();\n unregistered = true;\n } catch (error) {\n this.logCleanupError('unregister OpenTelemetry instrumentations', error);\n }\n }\n if (!unregistered) {\n registration.instrumentations.forEach((instrumentation) => {\n this.runCleanup(`disable ${instrumentation.instrumentationName}`, () => instrumentation.disable());\n });\n }\n\n const { faro, faroOtel } = registration;\n if (faro && faroOtel && faro.otel === faroOtel) {\n this.runCleanup('restore faro.otel', () => {\n if (registration.previousFaroOtel === undefined) {\n delete faro.otel;\n } else {\n faro.otel = registration.previousFaroOtel;\n }\n });\n }\n\n if (registration.ownsPropagator) {\n this.runCleanup('clear the OpenTelemetry propagator', () => propagation.disable());\n }\n if (registration.ownsContextManager) {\n this.runCleanup('clear the OpenTelemetry context manager', () => context.disable());\n } else if (registration.ownsContextManagerInstance && registration.contextManager) {\n this.runCleanup('disable the unused OpenTelemetry context manager', () => registration.contextManager?.disable());\n }\n if (registration.ownsTracerProvider) {\n this.runCleanup('clear the OpenTelemetry tracer provider', () => trace.disable());\n }\n\n return registration;\n }\n\n private runCleanup(action: string, cleanup: VoidFunction): void {\n try {\n cleanup();\n } catch (error) {\n this.logCleanupError(action, error);\n }\n }\n\n private logCleanupError(action: string, error: unknown): void {\n try {\n this.logError(`Failed to ${action}:`, error);\n } catch (_loggingError) {\n // Cleanup must not fail because a custom logger threw.\n }\n }\n\n private startProviderShutdown(registration: TracingRegistration): Promise<void> {\n if (!registration.shutdownPromise) {\n const shutdownPromise = Promise.resolve()\n .then(() => registration.provider.forceFlush())\n .catch((error) => {\n this.logCleanupError('flush the OpenTelemetry tracer provider', error);\n })\n .then(() => registration.provider.shutdown());\n registration.shutdownPromise = shutdownPromise;\n this.pendingShutdowns.add(shutdownPromise);\n void shutdownPromise.then(\n () => this.pendingShutdowns.delete(shutdownPromise),\n () => this.pendingShutdowns.delete(shutdownPromise)\n );\n }\n return registration.shutdownPromise;\n }\n\n private startSuppliedSpanProcessorShutdown(): Promise<void> | undefined {\n const spanProcessor = this.options.spanProcessor;\n if (!spanProcessor) {\n return undefined;\n }\n if (!this.suppliedSpanProcessorShutdown) {\n try {\n this.suppliedSpanProcessorShutdown = spanProcessor.shutdown();\n } catch (error) {\n this.suppliedSpanProcessorShutdown = Promise.reject(error);\n }\n }\n return this.suppliedSpanProcessorShutdown;\n }\n\n /** Detach request instrumentations and wait for the tracer provider to flush. */\n async shutdown(): Promise<void> {\n const pendingShutdowns = Array.from(this.pendingShutdowns);\n const registration = this.detachRegistration();\n if (registration) {\n pendingShutdowns.push(this.startProviderShutdown(registration));\n }\n\n let firstError: unknown;\n let shutdownFailed = false;\n for (const shutdownPromise of pendingShutdowns) {\n try {\n await shutdownPromise;\n } catch (error) {\n if (!shutdownFailed) {\n firstError = error;\n shutdownFailed = true;\n }\n }\n }\n const spanProcessorShutdown = this.startSuppliedSpanProcessorShutdown();\n if (spanProcessorShutdown) {\n try {\n await spanProcessorShutdown;\n } catch (error) {\n if (!shutdownFailed) {\n firstError = error;\n shutdownFailed = true;\n }\n }\n }\n if (shutdownFailed) {\n throw firstError;\n }\n }\n\n /** Detach synchronously when Faro removes this instrumentation. */\n destroy(): void {\n const registration = this.detachRegistration();\n if (!registration) {\n return;\n }\n void this.startProviderShutdown(registration).then(undefined, (error) => {\n this.logCleanupError('shut down the OpenTelemetry tracer provider', error);\n });\n }\n}\n"]}
|
|
@@ -23,9 +23,9 @@ var __rest = (this && this.__rest) || function (s, e) {
|
|
|
23
23
|
};
|
|
24
24
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
25
|
exports.getDefaultOTELInstrumentations = getDefaultOTELInstrumentations;
|
|
26
|
+
exports.updateDefaultOTELInstrumentations = updateDefaultOTELInstrumentations;
|
|
26
27
|
var instrumentation_fetch_1 = require("@opentelemetry/instrumentation-fetch");
|
|
27
28
|
var instrumentation_xml_http_request_1 = require("@opentelemetry/instrumentation-xml-http-request");
|
|
28
|
-
var faro_core_1 = require("@grafana/faro-core");
|
|
29
29
|
var instrumentationUtils_1 = require("./instrumentationUtils");
|
|
30
30
|
/**
|
|
31
31
|
* Get default OTEL instrumentations for React Native
|
|
@@ -44,37 +44,45 @@ var instrumentationUtils_1 = require("./instrumentationUtils");
|
|
|
44
44
|
*/
|
|
45
45
|
function getDefaultOTELInstrumentations(options) {
|
|
46
46
|
if (options === void 0) { options = {}; }
|
|
47
|
-
var _a = options
|
|
47
|
+
var _a = resolveDefaultInstrumentationOptions(options), enableFetchInstrumentation = _a.enableFetchInstrumentation, enableXhrInstrumentation = _a.enableXhrInstrumentation, fetchConfig = _a.fetchConfig, xhrConfig = _a.xhrConfig;
|
|
48
48
|
var instrumentations = [];
|
|
49
49
|
if (enableFetchInstrumentation) {
|
|
50
|
-
instrumentations.push(new instrumentation_fetch_1.FetchInstrumentation(
|
|
50
|
+
instrumentations.push(new instrumentation_fetch_1.FetchInstrumentation(fetchConfig));
|
|
51
51
|
}
|
|
52
52
|
if (enableXhrInstrumentation) {
|
|
53
|
-
instrumentations.push(new instrumentation_xml_http_request_1.XMLHttpRequestInstrumentation(
|
|
53
|
+
instrumentations.push(new instrumentation_xml_http_request_1.XMLHttpRequestInstrumentation(xhrConfig));
|
|
54
54
|
}
|
|
55
55
|
return instrumentations;
|
|
56
56
|
}
|
|
57
|
+
function updateDefaultOTELInstrumentations(instrumentations, options) {
|
|
58
|
+
if (options === void 0) { options = {}; }
|
|
59
|
+
var _a = resolveDefaultInstrumentationOptions(options), fetchConfig = _a.fetchConfig, xhrConfig = _a.xhrConfig;
|
|
60
|
+
instrumentations.forEach(function (instrumentation) {
|
|
61
|
+
if (instrumentation instanceof instrumentation_fetch_1.FetchInstrumentation) {
|
|
62
|
+
instrumentation.setConfig(fetchConfig);
|
|
63
|
+
}
|
|
64
|
+
else if (instrumentation instanceof instrumentation_xml_http_request_1.XMLHttpRequestInstrumentation) {
|
|
65
|
+
instrumentation.setConfig(xhrConfig);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function resolveDefaultInstrumentationOptions(options) {
|
|
70
|
+
var _a = options.enableFetchInstrumentation, enableFetchInstrumentation = _a === void 0 ? true : _a, _b = options.enableXhrInstrumentation, enableXhrInstrumentation = _b === void 0 ? false : _b, fetchInstrumentationOptions = options.fetchInstrumentationOptions, xhrInstrumentationOptions = options.xhrInstrumentationOptions, sharedOptions = __rest(options, ["enableFetchInstrumentation", "enableXhrInstrumentation", "fetchInstrumentationOptions", "xhrInstrumentationOptions"]);
|
|
71
|
+
return {
|
|
72
|
+
enableFetchInstrumentation: enableFetchInstrumentation,
|
|
73
|
+
enableXhrInstrumentation: enableXhrInstrumentation,
|
|
74
|
+
fetchConfig: createFetchInstrumentationOptions(fetchInstrumentationOptions, sharedOptions),
|
|
75
|
+
xhrConfig: createXhrInstrumentationOptions(xhrInstrumentationOptions, sharedOptions),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
57
78
|
function createFetchInstrumentationOptions(fetchInstrumentationOptions, sharedOptions) {
|
|
58
79
|
return __assign(__assign(__assign(__assign({}, sharedOptions), {
|
|
59
80
|
// Ignore network performance events to avoid duplicates
|
|
60
|
-
ignoreNetworkEvents: true }), fetchInstrumentationOptions), {
|
|
81
|
+
ignoreNetworkEvents: true }), fetchInstrumentationOptions), { semconvStabilityOptIn: 'http',
|
|
61
82
|
// Always keep this function
|
|
62
83
|
applyCustomAttributesOnSpan: (0, instrumentationUtils_1.fetchCustomAttributeFunctionWithDefaults)(fetchInstrumentationOptions === null || fetchInstrumentationOptions === void 0 ? void 0 : fetchInstrumentationOptions.applyCustomAttributesOnSpan),
|
|
63
|
-
//
|
|
64
|
-
requestHook:
|
|
65
|
-
try {
|
|
66
|
-
var currentAction = faro_core_1.faro.api.getActiveUserAction();
|
|
67
|
-
if (currentAction &&
|
|
68
|
-
(currentAction === null || currentAction === void 0 ? void 0 : currentAction.getState()) === faro_core_1.UserActionState.Started) {
|
|
69
|
-
span.setAttribute('faro.action.user.name', currentAction.name);
|
|
70
|
-
span.setAttribute('faro.action.user.parentId', currentAction.parentId);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
catch (_error) {
|
|
74
|
-
// Silently fail - don't log to avoid infinite loops
|
|
75
|
-
// The span will just not have user action context
|
|
76
|
-
}
|
|
77
|
-
} });
|
|
84
|
+
// Also supports callers using a custom processor without the RN request monitor.
|
|
85
|
+
requestHook: instrumentationUtils_1.captureFetchUserAction });
|
|
78
86
|
}
|
|
79
87
|
function createXhrInstrumentationOptions(xhrInstrumentationOptions, sharedOptions) {
|
|
80
88
|
return __assign(__assign(__assign(__assign({}, sharedOptions), { ignoreNetworkEvents: true }), xhrInstrumentationOptions), { applyCustomAttributesOnSpan: (0, instrumentationUtils_1.xhrCustomAttributeFunctionWithDefaults)(xhrInstrumentationOptions === null || xhrInstrumentationOptions === void 0 ? void 0 : xhrInstrumentationOptions.applyCustomAttributesOnSpan) });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getDefaultOTELInstrumentations.js","sourceRoot":"","sources":["../../../src/instrumentations/getDefaultOTELInstrumentations.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"getDefaultOTELInstrumentations.js","sourceRoot":"","sources":["../../../src/instrumentations/getDefaultOTELInstrumentations.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2BA,wEAeC;AAED,8EAaC;AAxDD,8EAA4E;AAC5E,oGAAgG;AAIhG,+DAIgC;AAEhC;;;;;;;;;;;;;;GAcG;AACH,SAAgB,8BAA8B,CAAC,OAA4C;IAA5C,wBAAA,EAAA,YAA4C;IACnF,IAAA,KACJ,oCAAoC,CAAC,OAAO,CAAC,EADvC,0BAA0B,gCAAA,EAAE,wBAAwB,8BAAA,EAAE,WAAW,iBAAA,EAAE,SAAS,eACrC,CAAC;IAEhD,IAAM,gBAAgB,GAA4B,EAAE,CAAC;IAErD,IAAI,0BAA0B,EAAE,CAAC;QAC/B,gBAAgB,CAAC,IAAI,CAAC,IAAI,4CAAoB,CAAC,WAAW,CAAC,CAAC,CAAC;IAC/D,CAAC;IAED,IAAI,wBAAwB,EAAE,CAAC;QAC7B,gBAAgB,CAAC,IAAI,CAAC,IAAI,gEAA6B,CAAC,SAAS,CAAC,CAAC,CAA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2BAA2B,CAAE,2BAA2B,CACzD;QACD,iFAAiF;QACjF,WAAW,EAAE,6CAAsB,IACnC;AACJ,CAAC;AAED,SAAS,+BAA+B,CACtC,yBAAsF,EACtF,aAAsC;IAEtC,+CACK,aAAa,KAChB,mBAAmB,EAAE,IAAI,KACtB,yBAAyB,KAC5B,2BAA2B,EAAE,IAAA,6DAAsC,EACjE,yBAAyB,aAAzB,yBAAyB,uBAAzB,yBAAyB,CAAE,2BAA2B,CACvD,IACD;AACJ,CAAC","sourcesContent":["import type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';\nimport { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';\n\nimport type { DefaultInstrumentationsOptions, InstrumentationOption } from '../types';\n\nimport {\n captureFetchUserAction,\n fetchCustomAttributeFunctionWithDefaults,\n xhrCustomAttributeFunctionWithDefaults,\n} from './instrumentationUtils';\n\n/**\n * Get default OTEL instrumentations for React Native\n *\n * This function creates the default OpenTelemetry instrumentations for React Native:\n * - FetchInstrumentation: Traces fetch() API calls\n * - XMLHttpRequestInstrumentation: Optional for apps that use XHR/axios directly\n *\n * IMPORTANT: Infinite loop prevention\n * - ignoreUrls is used to exclude Faro collector URLs\n * - ignoreNetworkEvents is true to avoid duplicate events\n * - No console logging during instrumentation\n *\n * @param options - Configuration options\n * @returns Array of OTEL instrumentations\n */\nexport function getDefaultOTELInstrumentations(options: DefaultInstrumentationsOptions = {}): InstrumentationOption[] {\n const { enableFetchInstrumentation, enableXhrInstrumentation, fetchConfig, xhrConfig } =\n resolveDefaultInstrumentationOptions(options);\n\n const instrumentations: InstrumentationOption[] = [];\n\n if (enableFetchInstrumentation) {\n instrumentations.push(new FetchInstrumentation(fetchConfig));\n }\n\n if (enableXhrInstrumentation) {\n instrumentations.push(new XMLHttpRequestInstrumentation(xhrConfig));\n }\n\n return instrumentations;\n}\n\nexport function updateDefaultOTELInstrumentations(\n instrumentations: Instrumentation[],\n options: DefaultInstrumentationsOptions = {}\n): void {\n const { fetchConfig, xhrConfig } = resolveDefaultInstrumentationOptions(options);\n\n instrumentations.forEach((instrumentation) => {\n if (instrumentation instanceof FetchInstrumentation) {\n instrumentation.setConfig(fetchConfig);\n } else if (instrumentation instanceof XMLHttpRequestInstrumentation) {\n instrumentation.setConfig(xhrConfig);\n }\n });\n}\n\nfunction resolveDefaultInstrumentationOptions(options: DefaultInstrumentationsOptions) {\n const {\n enableFetchInstrumentation = true,\n enableXhrInstrumentation = false,\n fetchInstrumentationOptions,\n xhrInstrumentationOptions,\n ...sharedOptions\n } = options;\n\n return {\n enableFetchInstrumentation,\n enableXhrInstrumentation,\n fetchConfig: createFetchInstrumentationOptions(fetchInstrumentationOptions, sharedOptions),\n xhrConfig: createXhrInstrumentationOptions(xhrInstrumentationOptions, sharedOptions),\n };\n}\n\nfunction createFetchInstrumentationOptions(\n fetchInstrumentationOptions: DefaultInstrumentationsOptions['fetchInstrumentationOptions'],\n sharedOptions: Record<string, unknown>\n) {\n return {\n ...sharedOptions,\n // Ignore network performance events to avoid duplicates\n ignoreNetworkEvents: true,\n // Keep this here to overwrite the defaults above if provided by the users\n ...fetchInstrumentationOptions,\n semconvStabilityOptIn: 'http',\n // Always keep this function\n applyCustomAttributesOnSpan: fetchCustomAttributeFunctionWithDefaults(\n fetchInstrumentationOptions?.applyCustomAttributesOnSpan\n ),\n // Also supports callers using a custom processor without the RN request monitor.\n requestHook: captureFetchUserAction,\n };\n}\n\nfunction createXhrInstrumentationOptions(\n xhrInstrumentationOptions: DefaultInstrumentationsOptions['xhrInstrumentationOptions'],\n sharedOptions: Record<string, unknown>\n) {\n return {\n ...sharedOptions,\n ignoreNetworkEvents: true,\n ...xhrInstrumentationOptions,\n applyCustomAttributesOnSpan: xhrCustomAttributeFunctionWithDefaults(\n xhrInstrumentationOptions?.applyCustomAttributesOnSpan\n ),\n };\n}\n"]}
|
|
@@ -1,11 +1,26 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.captureFetchUserAction = captureFetchUserAction;
|
|
3
4
|
exports.setSpanStatusOnFetchError = setSpanStatusOnFetchError;
|
|
4
5
|
exports.fetchCustomAttributeFunctionWithDefaults = fetchCustomAttributeFunctionWithDefaults;
|
|
5
6
|
exports.setSpanStatusOnXMLHttpRequestError = setSpanStatusOnXMLHttpRequestError;
|
|
6
7
|
exports.xhrCustomAttributeFunctionWithDefaults = xhrCustomAttributeFunctionWithDefaults;
|
|
7
8
|
var api_1 = require("@opentelemetry/api");
|
|
8
9
|
var faro_core_1 = require("@grafana/faro-core");
|
|
10
|
+
/** Capture request ownership at start, before the monitor can halt the action. */
|
|
11
|
+
function captureFetchUserAction(span) {
|
|
12
|
+
var _a, _b;
|
|
13
|
+
try {
|
|
14
|
+
var action = (_b = (_a = faro_core_1.faro.api) === null || _a === void 0 ? void 0 : _a.getActiveUserAction) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
15
|
+
if (action && action.getState() === faro_core_1.UserActionState.Started) {
|
|
16
|
+
span.setAttribute('faro.action.user.name', action.name);
|
|
17
|
+
span.setAttribute('faro.action.user.parentId', action.parentId);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
catch (_c) {
|
|
21
|
+
// Instrumentation must not interrupt the request or log recursively.
|
|
22
|
+
}
|
|
23
|
+
}
|
|
9
24
|
/**
|
|
10
25
|
* Set span status to ERROR when fetch fails
|
|
11
26
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentationUtils.js","sourceRoot":"","sources":["../../../src/instrumentations/instrumentationUtils.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"instrumentationUtils.js","sourceRoot":"","sources":["../../../src/instrumentations/instrumentationUtils.ts"],"names":[],"mappings":";;AAQA,wDAUC;AAgBD,8DAMC;AAiBD,4FAqBC;AAKD,gFAMC;AAqBD,wFAQC;AAtHD,0CAAoD;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,CAAC,EAAE,CAAC;QACX,2DAA2D;IAC7D,CAAC;AACH,CAAC;AAED;;GAEG;AACH,SAAgB,sCAAsC,CACpD,YAAyC;IAEzC,OAAO,UAAC,IAAU,EAAE,GAAmB;QACrC,kCAAkC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC9C,0BAA0B,CAAC,IAAI,CAAC,CAAC;QACjC,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAG,IAAI,EAAE,GAAG,CAAC,CAAC;IAC5B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { SpanStatusCode } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\nimport type { FetchCustomAttributeFunction } from '@opentelemetry/instrumentation-fetch';\nimport type { XHRCustomAttributeFunction } from '@opentelemetry/instrumentation-xml-http-request';\n\nimport { faro, type UserActionInternalInterface, UserActionState } from '@grafana/faro-core';\n\n/** Capture request ownership at start, before the monitor can halt the action. */\nexport function captureFetchUserAction(span: Span): void {\n try {\n const action = faro.api?.getActiveUserAction?.();\n if (action && (action as UserActionInternalInterface).getState() === UserActionState.Started) {\n span.setAttribute('faro.action.user.name', action.name);\n span.setAttribute('faro.action.user.parentId', action.parentId);\n }\n } catch {\n // Instrumentation must not interrupt the request or log recursively.\n }\n}\n\n/**\n * FetchError interface matching OpenTelemetry's internal type\n * Note: FetchError is not exported from @opentelemetry/instrumentation-fetch\n */\ninterface FetchError {\n status?: number;\n message: string;\n}\n\n/**\n * Set span status to ERROR when fetch fails\n *\n * This ensures that failed HTTP requests are marked as errors in traces.\n */\nexport function setSpanStatusOnFetchError(span: Span, error: Error | string): void {\n const message = typeof error === 'string' ? error : error.message;\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n}\n\n/**\n * Type guard to check if result is a FetchError\n */\nfunction isFetchError(result: Response | FetchError): result is FetchError {\n return 'message' in result && typeof (result as FetchError).message === 'string';\n}\n\n/**\n * Custom attribute function for fetch instrumentation with defaults\n *\n * Combines user-provided custom attributes with default handling.\n *\n * @param userFunction - Optional user-provided custom attribute function\n * @returns Combined custom attribute function\n */\nexport function fetchCustomAttributeFunctionWithDefaults(\n userFunction?: FetchCustomAttributeFunction\n): FetchCustomAttributeFunction {\n const fn: FetchCustomAttributeFunction = (\n span: Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ) => {\n // Call user function first if provided\n if (userFunction) {\n userFunction(span, request, result);\n }\n\n // Add default error handling\n if (isFetchError(result)) {\n setSpanStatusOnFetchError(span, result.message);\n } else if (result instanceof Response && result.status >= 400 && result.status < 600) {\n setSpanStatusOnFetchError(span, `HTTP ${result.status}: ${result.statusText}`);\n }\n };\n return fn;\n}\n\n/**\n * Set span status to ERROR for XHR failures (status 0 or 4xx/5xx).\n */\nexport function setSpanStatusOnXMLHttpRequestError(span: Span, xhr: XMLHttpRequest): void {\n const status = xhr.status;\n if (status == null) return;\n if (status === 0 || (status >= 400 && status < 600)) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n }\n}\n\n/**\n * Add user action context to span when active (for HTTP Errors column in user action table).\n */\nfunction addUserActionContextToSpan(span: Span): void {\n try {\n const currentAction = faro.api?.getActiveUserAction?.();\n const state = (currentAction as unknown as UserActionInternalInterface)?.getState?.();\n if (currentAction && (state === UserActionState.Started || state === UserActionState.Halted)) {\n span.setAttribute('faro.action.user.name', currentAction.name);\n span.setAttribute('faro.action.user.parentId', currentAction.parentId);\n }\n } catch (_) {\n // Silently fail - don't log to avoid instrumentation loops\n }\n}\n\n/**\n * Custom attribute function for XHR instrumentation with defaults.\n */\nexport function xhrCustomAttributeFunctionWithDefaults(\n userFunction?: XHRCustomAttributeFunction\n): XHRCustomAttributeFunction {\n return (span: Span, xhr: XMLHttpRequest) => {\n setSpanStatusOnXMLHttpRequestError(span, xhr);\n addUserActionContextToSpan(span);\n userFunction?.(span, xhr);\n };\n}\n"]}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.HttpRequestMonitorSpanProcessor = void 0;
|
|
4
|
+
var core_1 = require("@opentelemetry/core");
|
|
4
5
|
var faro_react_native_1 = require("@grafana/faro-react-native");
|
|
6
|
+
var instrumentationUtils_1 = require("../instrumentations/instrumentationUtils");
|
|
7
|
+
// Optional XHR instrumentation still emits these attributes.
|
|
5
8
|
var ATTR_HTTP_METHOD = 'http.method';
|
|
6
9
|
var ATTR_HTTP_STATUS_CODE = 'http.status_code';
|
|
7
10
|
var ATTR_HTTP_URL = 'http.url';
|
|
@@ -30,7 +33,16 @@ function getAttr(span, key) {
|
|
|
30
33
|
* Check if a span is an HTTP span (from FetchInstrumentation).
|
|
31
34
|
*/
|
|
32
35
|
function isHttpSpan(span) {
|
|
33
|
-
|
|
36
|
+
// url.full is shared by non-HTTP spans; stable HTTP spans identify their method at creation.
|
|
37
|
+
return getHttpMethod(span) != null || getAttr(span, ATTR_HTTP_URL) != null;
|
|
38
|
+
}
|
|
39
|
+
function getHttpUrl(span) {
|
|
40
|
+
var _a;
|
|
41
|
+
return (_a = getAttr(span, 'url.full')) !== null && _a !== void 0 ? _a : getAttr(span, ATTR_HTTP_URL);
|
|
42
|
+
}
|
|
43
|
+
function getHttpMethod(span) {
|
|
44
|
+
var _a;
|
|
45
|
+
return (_a = getAttr(span, 'http.request.method')) !== null && _a !== void 0 ? _a : getAttr(span, ATTR_HTTP_METHOD);
|
|
34
46
|
}
|
|
35
47
|
/**
|
|
36
48
|
* SpanProcessor that notifies httpRequestMonitor when HTTP spans start and end.
|
|
@@ -47,10 +59,15 @@ var HttpRequestMonitorSpanProcessor = /** @class */ (function () {
|
|
|
47
59
|
HttpRequestMonitorSpanProcessor.prototype.onStart = function (span, parentContext) {
|
|
48
60
|
var _a, _b;
|
|
49
61
|
if (isHttpSpan(span)) {
|
|
50
|
-
|
|
51
|
-
|
|
62
|
+
// Capture before notifyStart changes Started to Halted. New requests while
|
|
63
|
+
// already Halted are not tracked by the controller and must not inherit it.
|
|
64
|
+
if (span.instrumentationScope.name === '@opentelemetry/instrumentation-fetch') {
|
|
65
|
+
(0, instrumentationUtils_1.captureFetchUserAction)(span);
|
|
66
|
+
}
|
|
67
|
+
var url = (_a = getHttpUrl(span)) !== null && _a !== void 0 ? _a : '';
|
|
68
|
+
var method = (_b = getHttpMethod(span)) !== null && _b !== void 0 ? _b : 'GET';
|
|
52
69
|
var requestId = span.spanContext().spanId;
|
|
53
|
-
var startTimeMs =
|
|
70
|
+
var startTimeMs = (0, core_1.hrTimeToMilliseconds)(span.startTime);
|
|
54
71
|
var payload = {
|
|
55
72
|
requestId: requestId,
|
|
56
73
|
url: url,
|
|
@@ -62,18 +79,15 @@ var HttpRequestMonitorSpanProcessor = /** @class */ (function () {
|
|
|
62
79
|
this.processor.onStart(span, parentContext);
|
|
63
80
|
};
|
|
64
81
|
HttpRequestMonitorSpanProcessor.prototype.onEnd = function (span) {
|
|
65
|
-
var _a, _b;
|
|
82
|
+
var _a, _b, _c;
|
|
66
83
|
if (isHttpSpan(span)) {
|
|
67
|
-
var url = (_a =
|
|
68
|
-
var method = (_b =
|
|
84
|
+
var url = (_a = getHttpUrl(span)) !== null && _a !== void 0 ? _a : '';
|
|
85
|
+
var method = (_b = getHttpMethod(span)) !== null && _b !== void 0 ? _b : 'GET';
|
|
69
86
|
var requestId = span.spanContext().spanId;
|
|
70
|
-
var statusAttr = getAttr(span, ATTR_HTTP_STATUS_CODE);
|
|
87
|
+
var statusAttr = (_c = getAttr(span, 'http.response.status_code')) !== null && _c !== void 0 ? _c : getAttr(span, ATTR_HTTP_STATUS_CODE);
|
|
71
88
|
var status_1 = statusAttr != null ? parseInt(statusAttr, 10) : undefined;
|
|
72
|
-
var
|
|
73
|
-
var
|
|
74
|
-
var endNs = spanWithTime.endTimeUnixNano;
|
|
75
|
-
var startTimeMs = startNs != null && !Number.isNaN(Number(startNs)) ? Number(startNs) / 1000000 : Date.now();
|
|
76
|
-
var endTimeMs = endNs != null && !Number.isNaN(Number(endNs)) ? Number(endNs) / 1000000 : Date.now();
|
|
89
|
+
var startTimeMs = (0, core_1.hrTimeToMilliseconds)(span.startTime);
|
|
90
|
+
var endTimeMs = (0, core_1.hrTimeToMilliseconds)(span.endTime);
|
|
77
91
|
var payload = {
|
|
78
92
|
requestId: requestId,
|
|
79
93
|
url: url,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpRequestMonitorSpanProcessor.js","sourceRoot":"","sources":["../../../src/processors/httpRequestMonitorSpanProcessor.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"httpRequestMonitorSpanProcessor.js","sourceRoot":"","sources":["../../../src/processors/httpRequestMonitorSpanProcessor.ts"],"names":[],"mappings":";;;AACA,4CAA2D;AAG3D,gEAIoC;AAEpC,iFAAkF;AAElF,6DAA6D;AAC7D,IAAM,gBAAgB,GAAG,aAAa,CAAC;AACvC,IAAM,qBAAqB,GAAG,kBAAkB,CAAC;AACjD,IAAM,aAAa,GAAG,UAAU,CAAC;AAEjC;;;GAGG;AACH,SAAS,OAAO,CAAC,IAAyB,EAAE,GAAW;;IACrD,IAAM,KAAK,GAAG,IAAI,CAAC,UAAiD,CAAC;IACrE,IAAI,KAAK,IAAI,IAAI;QAAE,OAAO,SAAS,CAAC;IACpC,IAAM,GAAG,GAAG,OAAO,KAAK,CAAC,KAAK,CAAC,KAAK,UAAU,CAAC,CAAC,CAAE,KAAyC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACrH,IAAI,GAAG,IAAI,IAAI;QAAE,OAAO,SAAS,CAAC;IAClC,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;IACrE,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,aAAa,IAAI,GA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gBACzC,SAAS,WAAA;gBACT,GAAG,KAAA;gBACH,MAAM,QAAA;gBACN,SAAS,EAAE,WAAW;gBACtB,OAAO,EAAE,SAAS;gBAClB,MAAM,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,QAAM,CAAC,CAAC,CAAC,CAAC,QAAM,CAAC,CAAC,CAAC,SAAS;aACnD,CAAC;YACF,IAAA,wCAAoB,EAAC,OAAO,CAAC,CAAC;QAChC,CAAC;QAED,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC;IAED,oDAAU,GAAV;QACE,OAAO,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,CAAC;IACrC,CAAC;IAED,kDAAQ,GAAR;QACE,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IACnC,CAAC;IACH,sCAAC;AAAD,CAAC,AA1DD,IA0DC;AA1DY,0EAA+B","sourcesContent":["import type { Context } from '@opentelemetry/api';\nimport { hrTimeToMilliseconds } from '@opentelemetry/core';\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace-base';\n\nimport {\n type HttpRequestMessagePayload,\n notifyHttpRequestEnd,\n notifyHttpRequestStart,\n} from '@grafana/faro-react-native';\n\nimport { captureFetchUserAction } from '../instrumentations/instrumentationUtils';\n\n// Optional XHR instrumentation still emits these attributes.\nconst ATTR_HTTP_METHOD = 'http.method';\nconst ATTR_HTTP_STATUS_CODE = 'http.status_code';\nconst ATTR_HTTP_URL = 'http.url';\n\n/**\n * Get string attribute from span.\n * Handles both SDK attribute format and OTLP-style attribute values.\n */\nfunction getAttr(span: Span | ReadableSpan, key: string): string | undefined {\n const attrs = span.attributes as Record<string, unknown> | undefined;\n if (attrs == null) return undefined;\n const raw = typeof attrs['get'] === 'function' ? (attrs as { get: (k: string) => unknown })['get'](key) : attrs[key];\n if (raw == null) return undefined;\n if (typeof raw === 'string') return raw.length > 0 ? raw : undefined;\n if (typeof raw === 'object' && raw !== null && 'stringValue' in raw) {\n const s = String((raw as { stringValue?: string }).stringValue ?? '');\n return s.length > 0 ? s : undefined;\n }\n const str = String(raw);\n return str.length > 0 ? str : undefined;\n}\n\n/**\n * Check if a span is an HTTP span (from FetchInstrumentation).\n */\nfunction isHttpSpan(span: Span | ReadableSpan): boolean {\n // url.full is shared by non-HTTP spans; stable HTTP spans identify their method at creation.\n return getHttpMethod(span) != null || getAttr(span, ATTR_HTTP_URL) != null;\n}\n\nfunction getHttpUrl(span: Span | ReadableSpan): string | undefined {\n return getAttr(span, 'url.full') ?? getAttr(span, ATTR_HTTP_URL);\n}\n\nfunction getHttpMethod(span: Span | ReadableSpan): string | undefined {\n return getAttr(span, 'http.request.method') ?? getAttr(span, ATTR_HTTP_METHOD);\n}\n\n/**\n * SpanProcessor that notifies httpRequestMonitor when HTTP spans start and end.\n *\n * This enables user action correlation (UserActionController halt logic) when\n * TracingInstrumentation is used instead of HttpInstrumentation.\n *\n * IMPORTANT: Must not use console or trigger any instrumentation to avoid loops.\n */\nexport class HttpRequestMonitorSpanProcessor implements SpanProcessor {\n constructor(private readonly processor: SpanProcessor) {}\n\n onStart(span: Span, parentContext: Context): void {\n if (isHttpSpan(span)) {\n // Capture before notifyStart changes Started to Halted. New requests while\n // already Halted are not tracked by the controller and must not inherit it.\n if (span.instrumentationScope.name === '@opentelemetry/instrumentation-fetch') {\n captureFetchUserAction(span);\n }\n const url = getHttpUrl(span) ?? '';\n const method = getHttpMethod(span) ?? 'GET';\n const requestId = span.spanContext().spanId;\n const startTimeMs = hrTimeToMilliseconds(span.startTime);\n\n const payload: HttpRequestMessagePayload = {\n requestId,\n url,\n method,\n startTime: startTimeMs,\n };\n notifyHttpRequestStart(payload);\n }\n\n this.processor.onStart(span, parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n if (isHttpSpan(span)) {\n const url = getHttpUrl(span) ?? '';\n const method = getHttpMethod(span) ?? 'GET';\n const requestId = span.spanContext().spanId;\n const statusAttr = getAttr(span, 'http.response.status_code') ?? getAttr(span, ATTR_HTTP_STATUS_CODE);\n const status = statusAttr != null ? parseInt(statusAttr, 10) : undefined;\n const startTimeMs = hrTimeToMilliseconds(span.startTime);\n const endTimeMs = hrTimeToMilliseconds(span.endTime);\n\n const payload: HttpRequestMessagePayload = {\n requestId,\n url,\n method,\n startTime: startTimeMs,\n endTime: endTimeMs,\n status: !Number.isNaN(status) ? status : undefined,\n };\n notifyHttpRequestEnd(payload);\n }\n\n this.processor.onEnd(span);\n }\n\n forceFlush(): Promise<void> {\n return this.processor.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this.processor.shutdown();\n }\n}\n"]}
|
package/dist/cjs/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Attributes, ContextManager, TextMapPropagator } from '@opentelemetry/api';\nimport type { Instrumentation } from '@opentelemetry/instrumentation';\nimport type { FetchCustomAttributeFunction } from '@opentelemetry/instrumentation-fetch';\nimport type { XHRCustomAttributeFunction } from '@opentelemetry/instrumentation-xml-http-request';\nimport type { SpanProcessor } from '@opentelemetry/sdk-trace-base';\n\nimport type { API, Patterns } from '@grafana/faro-core';\n\nexport type InstrumentationOption = Instrumentation | Instrumentation[];\n\nexport interface FaroTraceExporterConfig {\n api: API;\n}\n\nexport interface TracingInstrumentationOptions {\n resourceAttributes?: Attributes;\n propagator?: TextMapPropagator;\n contextManager?: ContextManager;\n instrumentations?: InstrumentationOption[];\n spanProcessor?: SpanProcessor;\n instrumentationOptions?: Omit<DefaultInstrumentationsOptions, 'ignoreUrls'>;\n}\n\nexport type MatchUrlDefinitions = Patterns;\n\nexport type DefaultInstrumentationsOptions = {\n ignoreUrls?: MatchUrlDefinitions;\n propagateTraceHeaderCorsUrls?: MatchUrlDefinitions;\n enableFetchInstrumentation?: boolean;\n enableXhrInstrumentation?: boolean;\n\n fetchInstrumentationOptions?: {\n applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;\n ignoreNetworkEvents?: boolean;\n };\n\n xhrInstrumentationOptions?: {\n applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;\n ignoreNetworkEvents?: boolean;\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Attributes, ContextManager, TextMapPropagator } from '@opentelemetry/api';\nimport type { Instrumentation } from '@opentelemetry/instrumentation';\nimport type { FetchCustomAttributeFunction } from '@opentelemetry/instrumentation-fetch';\nimport type { XHRCustomAttributeFunction } from '@opentelemetry/instrumentation-xml-http-request';\nimport type { SpanProcessor } from '@opentelemetry/sdk-trace-base';\n\nimport type { API, Patterns } from '@grafana/faro-core';\n\nexport type InstrumentationOption = Instrumentation | Instrumentation[];\n\nexport interface FaroTraceExporterConfig {\n api: API;\n}\n\nexport interface TracingInstrumentationOptions {\n resourceAttributes?: Attributes;\n propagator?: TextMapPropagator;\n contextManager?: ContextManager;\n instrumentations?: InstrumentationOption[];\n /**\n * A caller-supplied processor. Faro removal flushes it so the tracing instrumentation can be re-added;\n * TracingInstrumentation.shutdown() shuts it down and is terminal for that processor.\n */\n spanProcessor?: SpanProcessor;\n instrumentationOptions?: Omit<DefaultInstrumentationsOptions, 'ignoreUrls'>;\n}\n\nexport type MatchUrlDefinitions = Patterns;\n\nexport type DefaultInstrumentationsOptions = {\n ignoreUrls?: MatchUrlDefinitions;\n propagateTraceHeaderCorsUrls?: MatchUrlDefinitions;\n enableFetchInstrumentation?: boolean;\n enableXhrInstrumentation?: boolean;\n\n fetchInstrumentationOptions?: {\n applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;\n ignoreNetworkEvents?: boolean;\n };\n\n xhrInstrumentationOptions?: {\n applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;\n ignoreNetworkEvents?: boolean;\n };\n};\n"]}
|
|
@@ -8,6 +8,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
});
|
|
9
9
|
};
|
|
10
10
|
import { ExportResultCode } from '@opentelemetry/core';
|
|
11
|
+
import { JSON_ENCODER } from '@opentelemetry/otlp-transformer/build/src/common/utils';
|
|
11
12
|
import { createExportTraceServiceRequest } from '@opentelemetry/otlp-transformer/build/src/trace/internal';
|
|
12
13
|
import { createInternalLogger } from '@grafana/faro-core';
|
|
13
14
|
const internalLogger = createInternalLogger();
|
|
@@ -35,7 +36,7 @@ export class FaroTraceExporter {
|
|
|
35
36
|
}
|
|
36
37
|
try {
|
|
37
38
|
// Convert spans to OTLP format
|
|
38
|
-
const traceEvent = createExportTraceServiceRequest(spans,
|
|
39
|
+
const traceEvent = createExportTraceServiceRequest(spans, JSON_ENCODER);
|
|
39
40
|
// Send traces to Faro
|
|
40
41
|
this.config.api.pushTraces(traceEvent);
|
|
41
42
|
// Send Faro events for CLIENT spans (HTTP requests, etc.)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"faroTraceExporter.js","sourceRoot":"","sources":["../../../src/exporters/faroTraceExporter.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,0DAA0D,CAAC;AAG3G,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE1D,MAAM,cAAc,GAAG,oBAAoB,EAAE,CAAC;AAI9C,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D;;;;;;;;;GASG;AACH,MAAM,OAAO,iBAAiB;IAG5B,YAAoB,MAA+B;QAA/B,WAAM,GAAN,MAAM,CAAyB;QAF3C,gBAAW,GAAG,KAAK,CAAC;IAE0B,CAAC;IAEvD,MAAM,CAAC,KAAqB,EAAE,cAA8C;QAC1E,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,cAAc,CAAC,KAAK,CAAC,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CAAC,aAAa,CAAC,CAAC;YAEzC,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;QACrD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,2BAA2B;YAC3B,cAAc,CAAC,KAAK,CAAC,2CAA2C,EAAE,KAAK,CAAC,CAAC;YACzE,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC;QACpD,CAAC;IACH,CAAC;IAEK,QAAQ;;YACZ,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;YACxB,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACpC,CAAC;KAAA;IAEK,UAAU;;YACd,4DAA4D;YAC5D,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACpC,CAAC;KAAA;CACF","sourcesContent":["import { ExportResultCode } from '@opentelemetry/core';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { JSON_ENCODER } from '@opentelemetry/otlp-transformer/build/src/common/utils';\nimport { createExportTraceServiceRequest } from '@opentelemetry/otlp-transformer/build/src/trace/internal';\nimport type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\n\nimport { createInternalLogger } from '@grafana/faro-core';\n\nconst internalLogger = createInternalLogger();\n\nimport type { FaroTraceExporterConfig } from '../types';\n\nimport { sendFaroEvents } from './faroTraceExporter.utils';\n\n/**\n * FaroTraceExporter for React Native\n *\n * Exports OpenTelemetry spans to Faro backend using pushTraces API.\n *\n * IMPORTANT: To avoid infinite loops:\n * - Uses internalLogger instead of console\n * - Does NOT log during export (except errors)\n * - Relies on Faro's internal deduplication\n */\nexport class FaroTraceExporter implements SpanExporter {\n private _isShutdown = false;\n\n constructor(private config: FaroTraceExporterConfig) {}\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n if (this._isShutdown) {\n internalLogger.error('FaroTraceExporter: Cannot export spans, exporter is shut down');\n resultCallback({ code: ExportResultCode.FAILED });\n return;\n }\n\n try {\n // Convert spans to OTLP format\n const traceEvent = createExportTraceServiceRequest(spans, JSON_ENCODER);\n\n // Send traces to Faro\n this.config.api.pushTraces(traceEvent);\n\n // Send Faro events for CLIENT spans (HTTP requests, etc.)\n // This is done WITHOUT logging to avoid infinite loops\n sendFaroEvents(traceEvent.resourceSpans);\n\n resultCallback({ code: ExportResultCode.SUCCESS });\n } catch (error) {\n // Only log critical errors\n internalLogger.error('FaroTraceExporter: Failed to export spans', error);\n resultCallback({ code: ExportResultCode.FAILED });\n }\n }\n\n async shutdown(): Promise<void> {\n this._isShutdown = true;\n return Promise.resolve(undefined);\n }\n\n async forceFlush(): Promise<void> {\n // No-op for now - spans are sent immediately via pushTraces\n return Promise.resolve(undefined);\n }\n}\n"]}
|
|
@@ -2,6 +2,35 @@ import { ESpanKind } from '@opentelemetry/otlp-transformer/build/src/trace/inter
|
|
|
2
2
|
import { createInternalLogger, faro, unknownString } from '@grafana/faro-core';
|
|
3
3
|
const internalLogger = createInternalLogger();
|
|
4
4
|
const DURATION_NS_KEY = 'duration_ns';
|
|
5
|
+
/** Map stable OTel span attributes to Faro's fetch event contract. */
|
|
6
|
+
function projectFetchEventAttributes(attributes) {
|
|
7
|
+
var _a, _b, _c;
|
|
8
|
+
const fields = {
|
|
9
|
+
'http.request.method': 'http.method',
|
|
10
|
+
'url.full': 'http.url',
|
|
11
|
+
'http.response.status_code': 'http.status_code',
|
|
12
|
+
};
|
|
13
|
+
for (const [spanField, eventField] of Object.entries(fields)) {
|
|
14
|
+
if (attributes[spanField] != null) {
|
|
15
|
+
attributes[eventField] = attributes[spanField];
|
|
16
|
+
delete attributes[spanField];
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const url = attributes['http.url'];
|
|
20
|
+
if (url) {
|
|
21
|
+
try {
|
|
22
|
+
const parsed = new URL(url);
|
|
23
|
+
attributes['http.host'] = (_a = attributes['http.host']) !== null && _a !== void 0 ? _a : parsed.host;
|
|
24
|
+
attributes['http.scheme'] = (_b = attributes['http.scheme']) !== null && _b !== void 0 ? _b : parsed.protocol.replace(':', '');
|
|
25
|
+
}
|
|
26
|
+
catch (_d) {
|
|
27
|
+
// Keep the captured URL even if it cannot supply host/scheme metadata.
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
delete attributes['server.address'];
|
|
31
|
+
delete attributes['server.port'];
|
|
32
|
+
attributes['component'] = (_c = attributes['component']) !== null && _c !== void 0 ? _c : 'fetch';
|
|
33
|
+
}
|
|
5
34
|
/**
|
|
6
35
|
* Send Faro events for CLIENT spans (HTTP requests, navigation, etc.)
|
|
7
36
|
*
|
|
@@ -38,6 +67,9 @@ export function sendFaroEvents(resourceSpans = []) {
|
|
|
38
67
|
for (const attribute of span.attributes) {
|
|
39
68
|
faroEventAttributes[attribute.key] = String(Object.values(attribute.value)[0]);
|
|
40
69
|
}
|
|
70
|
+
if ((scope === null || scope === void 0 ? void 0 : scope.name) === '@opentelemetry/instrumentation-fetch') {
|
|
71
|
+
projectFetchEventAttributes(faroEventAttributes);
|
|
72
|
+
}
|
|
41
73
|
// Add span duration in nanoseconds
|
|
42
74
|
if (!Number.isNaN(span.endTimeUnixNano) && !Number.isNaN(span.startTimeUnixNano)) {
|
|
43
75
|
faroEventAttributes[DURATION_NS_KEY] = String(Number(span.endTimeUnixNano) - Number(span.startTimeUnixNano));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"faroTraceExporter.utils.js","sourceRoot":"","sources":["../../../src/exporters/faroTraceExporter.utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAuB,MAAM,gEAAgE,CAAC;AAEhH,OAAO,EAAE,oBAAoB,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAG/E,MAAM,cAAc,GAAG,oBAAoB,EAAE,CAAC;AAE9C,MAAM,eAAe,GAAG,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"faroTraceEx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mB,CAAC,uBAAuB,CAAC,IAAI,IAAI;gCACpD,mBAAmB,CAAC,2BAA2B,CAAC,IAAI,IAAI,EACxD,CAAC;gCACD,OAAO,CAAC,MAAM,GAAG;oCACf,IAAI,EAAE,mBAAmB,CAAC,uBAAuB,CAAC;oCAClD,QAAQ,EAAE,mBAAmB,CAAC,2BAA2B,CAAC;iCAC3D,CAAC;gCAEK,MAAA,OAAO,CAAC,UAAU,+CAAG,uBAAuB,CAAC,CAAC;gCAC9C,MAAA,OAAO,CAAC,UAAU,+CAAG,2BAA2B,CAAC,CAAC;4BAC3D,CAAC;4BAED,OAAO,OAAO,CAAC;wBACjB,CAAC;qBACF,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,iDAAiD;QACjD,+DAA+D;QAC/D,cAAc,CAAC,KAAK,CAAC,yCAAyC,EAAE,KAAK,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import type { SpanContext } from '@opentelemetry/api';\nimport { ESpanKind, type IResourceSpans } from '@opentelemetry/otlp-transformer/build/src/trace/internal-types';\n\nimport { createInternalLogger, faro, unknownString } from '@grafana/faro-core';\nimport type { EventAttributes as FaroEventAttributes } from '@grafana/faro-core';\n\nconst internalLogger = createInternalLogger();\n\nconst DURATION_NS_KEY = 'duration_ns';\n/** Map stable OTel span attributes to Faro's fetch event contract. */\nfunction projectFetchEventAttributes(attributes: FaroEventAttributes): void {\n const fields = {\n 'http.request.method': 'http.method',\n 'url.full': 'http.url',\n 'http.response.status_code': 'http.status_code',\n };\n for (const [spanField, eventField] of Object.entries(fields)) {\n if (attributes[spanField] != null) {\n attributes[eventField] = attributes[spanField];\n delete attributes[spanField];\n }\n }\n\n const url = attributes['http.url'];\n if (url) {\n try {\n const parsed = new URL(url);\n attributes['http.host'] = attributes['http.host'] ?? parsed.host;\n attributes['http.scheme'] = attributes['http.scheme'] ?? parsed.protocol.replace(':', '');\n } catch {\n // Keep the captured URL even if it cannot supply host/scheme metadata.\n }\n }\n delete attributes['server.address'];\n delete attributes['server.port'];\n attributes['component'] = attributes['component'] ?? 'fetch';\n}\n\n/**\n * Send Faro events for CLIENT spans (HTTP requests, navigation, etc.)\n *\n * IMPORTANT: This function is called during trace export and must be careful to avoid infinite loops.\n *\n * Infinite loop prevention strategy:\n * 1. Only process SPAN_KIND_CLIENT spans (HTTP requests, etc.)\n * 2. Use faro.api.pushEvent which:\n * - Does NOT trigger console logs if ConsoleInstrumentation is configured properly\n * - Does NOT trigger HTTP instrumentation for collector URLs (they're ignored)\n * 3. Use internalLogger for debugging instead of console\n * 4. Never call console.log/warn/error in this function\n *\n * @param resourceSpans - OTLP resource spans from trace exporter\n */\nexport function sendFaroEvents(resourceSpans: IResourceSpans[] = []) {\n try {\n for (const resourceSpan of resourceSpans) {\n const { scopeSpans } = resourceSpan;\n\n for (const scopeSpan of scopeSpans) {\n const { scope, spans = [] } = scopeSpan;\n\n for (const span of spans) {\n // Only process CLIENT spans (HTTP requests, external calls)\n // This avoids processing internal spans which could cause loops\n if (span.kind !== ESpanKind.SPAN_KIND_CLIENT) {\n continue;\n }\n\n const spanContext: Pick<SpanContext, 'traceId' | 'spanId'> = {\n traceId: span.traceId.toString(),\n spanId: span.spanId.toString(),\n };\n\n const faroEventAttributes: FaroEventAttributes = {};\n for (const attribute of span.attributes) {\n faroEventAttributes[attribute.key] = String(Object.values(attribute.value)[0]);\n }\n\n if (scope?.name === '@opentelemetry/instrumentation-fetch') {\n projectFetchEventAttributes(faroEventAttributes);\n }\n\n // Add span duration in nanoseconds\n if (!Number.isNaN(span.endTimeUnixNano) && !Number.isNaN(span.startTimeUnixNano)) {\n faroEventAttributes[DURATION_NS_KEY] = String(\n Number(span.endTimeUnixNano) - Number(span.startTimeUnixNano)\n );\n }\n\n const index = (scope?.name ?? '').indexOf('-');\n let eventName = unknownString;\n\n if (scope?.name) {\n if (index === -1) {\n eventName = scope.name.split('/')[1] ?? scope.name;\n }\n\n if (index > -1) {\n eventName = scope?.name.substring(index + 1);\n }\n }\n\n // Push event to Faro\n // This should NOT cause infinite loops because:\n // 1. The collector URL is in ignoreUrls for HttpInstrumentation\n // 2. ConsoleInstrumentation won't log this event\n // 3. No console.log calls are made here\n faro.api.pushEvent(`faro.tracing.${eventName}`, faroEventAttributes, undefined, {\n spanContext,\n // Convert nanoseconds to milliseconds\n timestampOverwriteMs: Number(span.endTimeUnixNano) / 1_000_000,\n customPayloadTransformer: (payload) => {\n if (\n faroEventAttributes['faro.action.user.name'] != null &&\n faroEventAttributes['faro.action.user.parentId'] != null\n ) {\n payload.action = {\n name: faroEventAttributes['faro.action.user.name'],\n parentId: faroEventAttributes['faro.action.user.parentId'],\n };\n\n delete payload.attributes?.['faro.action.user.name'];\n delete payload.attributes?.['faro.action.user.parentId'];\n }\n\n return payload;\n },\n });\n }\n }\n }\n } catch (error) {\n // Only log critical errors using internal logger\n // Do NOT use console.log here as it could cause infinite loops\n internalLogger.error('sendFaroEvents: Failed to process spans', error);\n }\n}\n"]}
|