🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@opentelemetry/sdk-trace-base

Package Overview
Dependencies
Maintainers
6
Versions
77
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opentelemetry/sdk-trace-base - npm Package Compare versions

Comparing version
2.8.0
to
2.9.0
+11
build/esm/BasicTracerProvider-shim.d.ts
import type { TracerConfig } from './types-shim';
import { TracerProvider } from '@opentelemetry/sdk-trace';
/**
* A TracerProvider implementation that reads configuration defaults from
* OTEL_* environment variables per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export declare class BasicTracerProvider extends TracerProvider {
constructor(config?: TracerConfig);
}
//# sourceMappingURL=BasicTracerProvider-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { merge } from '@opentelemetry/core';
import { loadDefaultConfig } from './config';
import { reconfigureLimits } from './utility';
import { TracerProvider } from '@opentelemetry/sdk-trace';
/**
* A TracerProvider implementation that reads configuration defaults from
* OTEL_* environment variables per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export class BasicTracerProvider extends TracerProvider {
constructor(config = {}) {
const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
delete mergedConfig.generalLimits;
super(mergedConfig);
}
}
//# sourceMappingURL=BasicTracerProvider-shim.js.map
{"version":3,"file":"BasicTracerProvider-shim.js","sourceRoot":"","sources":["../../src/BasicTracerProvider-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAE7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,cAAc;IACrD,YAAY,SAAuB,EAAE;QACnC,MAAM,YAAY,GAAG,KAAK,CACxB,EAAE,EACF,iBAAiB,EAAE,EACnB,iBAAiB,CAAC,MAAM,CAAC,CAC1B,CAAC;QACF,OAAO,YAAY,CAAC,aAAa,CAAC;QAClC,KAAK,CAAC,YAAY,CAAC,CAAC;IACtB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { merge } from '@opentelemetry/core';\nimport { loadDefaultConfig } from './config';\nimport type { TracerConfig } from './types-shim';\nimport { reconfigureLimits } from './utility';\nimport { TracerProvider } from '@opentelemetry/sdk-trace';\n\n/**\n * A TracerProvider implementation that reads configuration defaults from\n * OTEL_* environment variables per\n * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/\n */\nexport class BasicTracerProvider extends TracerProvider {\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n delete mergedConfig.generalLimits;\n super(mergedConfig);\n }\n}\n"]}
import type { SpanExporter } from '@opentelemetry/sdk-trace';
import { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';
import type { BatchSpanProcessorBrowserConfig, BufferConfig } from './types-shim';
/**
* A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export declare class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {
constructor(exporter: SpanExporter, config?: BufferConfig | BatchSpanProcessorBrowserConfig);
}
//# sourceMappingURL=BatchSpanProcessor-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { getNumberFromEnv } from '@opentelemetry/core';
import { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';
/**
* A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {
constructor(exporter, config) {
if (!config) {
config = {};
}
const envFallbacks = [
['maxExportBatchSize', 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE'],
['maxQueueSize', 'OTEL_BSP_MAX_QUEUE_SIZE'],
['scheduledDelayMillis', 'OTEL_BSP_SCHEDULE_DELAY'],
['exportTimeoutMillis', 'OTEL_BSP_EXPORT_TIMEOUT'],
];
for (const [configName, envName] of envFallbacks) {
if (config[configName] === undefined) {
const envFallback = getNumberFromEnv(envName);
if (envFallback !== undefined) {
config[configName] = envFallback;
}
}
}
super({ exporter, ...config });
}
}
//# sourceMappingURL=BatchSpanProcessor-shim.js.map
{"version":3,"file":"BatchSpanProcessor-shim.js","sourceRoot":"","sources":["../../src/BatchSpanProcessor-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,EAAE,kBAAkB,IAAI,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAM7F;;;GAGG;AACH,MAAM,OAAO,kBAAmB,SAAQ,2BAA2B;IACjE,YACE,QAAsB,EACtB,MAAuD;QAEvD,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,GAAG,EAAE,CAAC;SACb;QACD,MAAM,YAAY,GAAmC;YACnD,CAAC,oBAAoB,EAAE,gCAAgC,CAAC;YACxD,CAAC,cAAc,EAAE,yBAAyB,CAAC;YAC3C,CAAC,sBAAsB,EAAE,yBAAyB,CAAC;YACnD,CAAC,qBAAqB,EAAE,yBAAyB,CAAC;SACnD,CAAC;QACF,KAAK,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,YAAY,EAAE;YAChD,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,SAAS,EAAE;gBACpC,MAAM,WAAW,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;gBAC9C,IAAI,WAAW,KAAK,SAAS,EAAE;oBAC7B,MAAM,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;iBAClC;aACF;SACF;QAED,KAAK,CAAC,EAAE,QAAQ,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACjC,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getNumberFromEnv } from '@opentelemetry/core';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace';\nimport { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';\nimport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n} from './types-shim';\n\n/**\n * A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per\n * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/\n */\nexport class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {\n constructor(\n exporter: SpanExporter,\n config?: BufferConfig | BatchSpanProcessorBrowserConfig\n ) {\n if (!config) {\n config = {};\n }\n const envFallbacks: [keyof BufferConfig, string][] = [\n ['maxExportBatchSize', 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE'],\n ['maxQueueSize', 'OTEL_BSP_MAX_QUEUE_SIZE'],\n ['scheduledDelayMillis', 'OTEL_BSP_SCHEDULE_DELAY'],\n ['exportTimeoutMillis', 'OTEL_BSP_EXPORT_TIMEOUT'],\n ];\n for (const [configName, envName] of envFallbacks) {\n if (config[configName] === undefined) {\n const envFallback = getNumberFromEnv(envName);\n if (envFallback !== undefined) {\n config[configName] = envFallback;\n }\n }\n }\n\n super({ exporter, ...config });\n }\n}\n"]}
export { BasicTracerProvider } from './BasicTracerProvider-shim';
export type { BufferConfig, BatchSpanProcessorBrowserConfig, GeneralLimits, TracerConfig, SDKRegistrationConfig, } from './types-shim';
export { BatchSpanProcessor } from './BatchSpanProcessor-shim';
export { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';
export { ConsoleSpanExporter, RandomIdGenerator, InMemorySpanExporter, NoopSpanProcessor, AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler, SamplingDecision, } from '@opentelemetry/sdk-trace';
export type { ReadableSpan, SpanExporter, Sampler, SamplingResult, Span, SpanProcessor, TimedEvent, SpanLimits, IdGenerator, } from '@opentelemetry/sdk-trace';
//# sourceMappingURL=index-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BasicTracerProvider } from './BasicTracerProvider-shim';
export { BatchSpanProcessor } from './BatchSpanProcessor-shim';
export { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';
export { ConsoleSpanExporter, RandomIdGenerator, InMemorySpanExporter, NoopSpanProcessor, AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler, SamplingDecision, } from '@opentelemetry/sdk-trace';
//# sourceMappingURL=index-shim.js.map
{"version":3,"file":"index-shim.js","sourceRoot":"","sources":["../../src/index-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAQjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,0BAA0B,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BasicTracerProvider } from './BasicTracerProvider-shim';\nexport type {\n BufferConfig,\n BatchSpanProcessorBrowserConfig,\n GeneralLimits,\n TracerConfig,\n SDKRegistrationConfig,\n} from './types-shim';\nexport { BatchSpanProcessor } from './BatchSpanProcessor-shim';\nexport { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';\n\nexport {\n ConsoleSpanExporter,\n RandomIdGenerator,\n InMemorySpanExporter,\n NoopSpanProcessor,\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n SamplingDecision,\n} from '@opentelemetry/sdk-trace';\nexport type {\n ReadableSpan,\n SpanExporter,\n Sampler,\n SamplingResult,\n Span,\n SpanProcessor,\n TimedEvent,\n SpanLimits,\n IdGenerator,\n} from '@opentelemetry/sdk-trace';\n"]}
import type { SpanExporter } from '@opentelemetry/sdk-trace';
import { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';
/**
* A SimpleSpanProcessor with the old constructor call signature that
* takes just a single exporter argument. This version does not support
* the additional options that the SimpleSpanProcessor in sdk-trace does.
*/
export declare class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {
constructor(exporter: SpanExporter);
}
//# sourceMappingURL=SimpleSpanProcessor-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';
/**
* A SimpleSpanProcessor with the old constructor call signature that
* takes just a single exporter argument. This version does not support
* the additional options that the SimpleSpanProcessor in sdk-trace does.
*/
export class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {
constructor(exporter) {
super({ exporter });
}
}
//# sourceMappingURL=SimpleSpanProcessor-shim.js.map
{"version":3,"file":"SimpleSpanProcessor-shim.js","sourceRoot":"","sources":["../../src/SimpleSpanProcessor-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,mBAAmB,IAAI,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAE9F;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,2BAA2B;IAClE,YAAY,QAAsB;QAChC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;IACtB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from '@opentelemetry/sdk-trace';\nimport { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';\n\n/**\n * A SimpleSpanProcessor with the old constructor call signature that\n * takes just a single exporter argument. This version does not support\n * the additional options that the SimpleSpanProcessor in sdk-trace does.\n */\nexport class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {\n constructor(exporter: SpanExporter) {\n super({ exporter });\n }\n}\n"]}
import type { ContextManager, TextMapPropagator } from '@opentelemetry/api';
import type { TracerProviderOptions } from '@opentelemetry/sdk-trace';
/**
* TracerConfig provides an interface for configuring a BasicTracerProvider.
*/
export interface TracerConfig extends TracerProviderOptions {
/** General Limits */
generalLimits?: GeneralLimits;
}
/** Global configuration limits of trace service */
export interface GeneralLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per trace */
attributeCountLimit?: number;
}
/**
* Configuration options for registering the API with the SDK.
* Undefined values may be substituted for defaults, and null
* values will not be registered.
*/
export interface SDKRegistrationConfig {
/** Propagator to register as the global propagator */
propagator?: TextMapPropagator | null;
/** Context manager to register as the global context manager */
contextManager?: ContextManager | null;
}
/** Interface configuration for a buffer. */
export interface BufferConfig {
/** The maximum batch size of every export. It must be smaller or equal to
* maxQueueSize. The default value is 512. */
maxExportBatchSize?: number;
/** The delay interval in milliseconds between two consecutive exports.
* The default value is 5000ms. */
scheduledDelayMillis?: number;
/** How long the export can run before it is cancelled.
* The default value is 30000ms */
exportTimeoutMillis?: number;
/** The maximum queue size. After the size is reached spans are dropped.
* The default value is 2048. */
maxQueueSize?: number;
}
/** Interface configuration for BatchSpanProcessor on browser */
export interface BatchSpanProcessorBrowserConfig extends BufferConfig {
/** Disable flush when a user navigates to a new page, closes the tab or the browser, or,
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}
//# sourceMappingURL=types-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=types-shim.js.map
{"version":3,"file":"types-shim.js","sourceRoot":"","sources":["../../src/types-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ContextManager, TextMapPropagator } from '@opentelemetry/api';\nimport type { TracerProviderOptions } from '@opentelemetry/sdk-trace';\n\n/**\n * TracerConfig provides an interface for configuring a BasicTracerProvider.\n */\nexport interface TracerConfig extends TracerProviderOptions {\n /** General Limits */\n generalLimits?: GeneralLimits;\n}\n\n/** Global configuration limits of trace service */\nexport interface GeneralLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per trace */\n attributeCountLimit?: number;\n}\n\n/**\n * Configuration options for registering the API with the SDK.\n * Undefined values may be substituted for defaults, and null\n * values will not be registered.\n */\nexport interface SDKRegistrationConfig {\n /** Propagator to register as the global propagator */\n propagator?: TextMapPropagator | null;\n\n /** Context manager to register as the global context manager */\n contextManager?: ContextManager | null;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached spans are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\n/** Interface configuration for BatchSpanProcessor on browser */\nexport interface BatchSpanProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n"]}
import type { TracerConfig } from './types-shim';
import { TracerProvider } from '@opentelemetry/sdk-trace';
/**
* A TracerProvider implementation that reads configuration defaults from
* OTEL_* environment variables per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export declare class BasicTracerProvider extends TracerProvider {
constructor(config?: TracerConfig);
}
//# sourceMappingURL=BasicTracerProvider-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { merge } from '@opentelemetry/core';
import { loadDefaultConfig } from './config';
import { reconfigureLimits } from './utility';
import { TracerProvider } from '@opentelemetry/sdk-trace';
/**
* A TracerProvider implementation that reads configuration defaults from
* OTEL_* environment variables per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export class BasicTracerProvider extends TracerProvider {
constructor(config = {}) {
const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
delete mergedConfig.generalLimits;
super(mergedConfig);
}
}
//# sourceMappingURL=BasicTracerProvider-shim.js.map
{"version":3,"file":"BasicTracerProvider-shim.js","sourceRoot":"","sources":["../../src/BasicTracerProvider-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAE7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,cAAc;IACrD,YAAY,SAAuB,EAAE;QACnC,MAAM,YAAY,GAAG,KAAK,CACxB,EAAE,EACF,iBAAiB,EAAE,EACnB,iBAAiB,CAAC,MAAM,CAAC,CAC1B,CAAC;QACF,OAAO,YAAY,CAAC,aAAa,CAAC;QAClC,KAAK,CAAC,YAAY,CAAC,CAAC;IACtB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { merge } from '@opentelemetry/core';\nimport { loadDefaultConfig } from './config';\nimport type { TracerConfig } from './types-shim';\nimport { reconfigureLimits } from './utility';\nimport { TracerProvider } from '@opentelemetry/sdk-trace';\n\n/**\n * A TracerProvider implementation that reads configuration defaults from\n * OTEL_* environment variables per\n * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/\n */\nexport class BasicTracerProvider extends TracerProvider {\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n delete mergedConfig.generalLimits;\n super(mergedConfig);\n }\n}\n"]}
import type { SpanExporter } from '@opentelemetry/sdk-trace';
import { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';
import type { BatchSpanProcessorBrowserConfig, BufferConfig } from './types-shim';
/**
* A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export declare class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {
constructor(exporter: SpanExporter, config?: BufferConfig | BatchSpanProcessorBrowserConfig);
}
//# sourceMappingURL=BatchSpanProcessor-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { getNumberFromEnv } from '@opentelemetry/core';
import { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';
/**
* A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {
constructor(exporter, config) {
if (!config) {
config = {};
}
const envFallbacks = [
['maxExportBatchSize', 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE'],
['maxQueueSize', 'OTEL_BSP_MAX_QUEUE_SIZE'],
['scheduledDelayMillis', 'OTEL_BSP_SCHEDULE_DELAY'],
['exportTimeoutMillis', 'OTEL_BSP_EXPORT_TIMEOUT'],
];
for (const [configName, envName] of envFallbacks) {
if (config[configName] === undefined) {
const envFallback = getNumberFromEnv(envName);
if (envFallback !== undefined) {
config[configName] = envFallback;
}
}
}
super({ exporter, ...config });
}
}
//# sourceMappingURL=BatchSpanProcessor-shim.js.map
{"version":3,"file":"BatchSpanProcessor-shim.js","sourceRoot":"","sources":["../../src/BatchSpanProcessor-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,EAAE,kBAAkB,IAAI,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAM7F;;;GAGG;AACH,MAAM,OAAO,kBAAmB,SAAQ,2BAA2B;IACjE,YACE,QAAsB,EACtB,MAAuD;QAEvD,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,GAAG,EAAE,CAAC;SACb;QACD,MAAM,YAAY,GAAmC;YACnD,CAAC,oBAAoB,EAAE,gCAAgC,CAAC;YACxD,CAAC,cAAc,EAAE,yBAAyB,CAAC;YAC3C,CAAC,sBAAsB,EAAE,yBAAyB,CAAC;YACnD,CAAC,qBAAqB,EAAE,yBAAyB,CAAC;SACnD,CAAC;QACF,KAAK,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,YAAY,EAAE;YAChD,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,SAAS,EAAE;gBACpC,MAAM,WAAW,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;gBAC9C,IAAI,WAAW,KAAK,SAAS,EAAE;oBAC7B,MAAM,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;iBAClC;aACF;SACF;QAED,KAAK,CAAC,EAAE,QAAQ,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACjC,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getNumberFromEnv } from '@opentelemetry/core';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace';\nimport { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';\nimport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n} from './types-shim';\n\n/**\n * A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per\n * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/\n */\nexport class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {\n constructor(\n exporter: SpanExporter,\n config?: BufferConfig | BatchSpanProcessorBrowserConfig\n ) {\n if (!config) {\n config = {};\n }\n const envFallbacks: [keyof BufferConfig, string][] = [\n ['maxExportBatchSize', 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE'],\n ['maxQueueSize', 'OTEL_BSP_MAX_QUEUE_SIZE'],\n ['scheduledDelayMillis', 'OTEL_BSP_SCHEDULE_DELAY'],\n ['exportTimeoutMillis', 'OTEL_BSP_EXPORT_TIMEOUT'],\n ];\n for (const [configName, envName] of envFallbacks) {\n if (config[configName] === undefined) {\n const envFallback = getNumberFromEnv(envName);\n if (envFallback !== undefined) {\n config[configName] = envFallback;\n }\n }\n }\n\n super({ exporter, ...config });\n }\n}\n"]}
export { BasicTracerProvider } from './BasicTracerProvider-shim';
export type { BufferConfig, BatchSpanProcessorBrowserConfig, GeneralLimits, TracerConfig, SDKRegistrationConfig, } from './types-shim';
export { BatchSpanProcessor } from './BatchSpanProcessor-shim';
export { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';
export { ConsoleSpanExporter, RandomIdGenerator, InMemorySpanExporter, NoopSpanProcessor, AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler, SamplingDecision, } from '@opentelemetry/sdk-trace';
export type { ReadableSpan, SpanExporter, Sampler, SamplingResult, Span, SpanProcessor, TimedEvent, SpanLimits, IdGenerator, } from '@opentelemetry/sdk-trace';
//# sourceMappingURL=index-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BasicTracerProvider } from './BasicTracerProvider-shim';
export { BatchSpanProcessor } from './BatchSpanProcessor-shim';
export { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';
export { ConsoleSpanExporter, RandomIdGenerator, InMemorySpanExporter, NoopSpanProcessor, AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler, SamplingDecision, } from '@opentelemetry/sdk-trace';
//# sourceMappingURL=index-shim.js.map
{"version":3,"file":"index-shim.js","sourceRoot":"","sources":["../../src/index-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAQjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,0BAA0B,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BasicTracerProvider } from './BasicTracerProvider-shim';\nexport type {\n BufferConfig,\n BatchSpanProcessorBrowserConfig,\n GeneralLimits,\n TracerConfig,\n SDKRegistrationConfig,\n} from './types-shim';\nexport { BatchSpanProcessor } from './BatchSpanProcessor-shim';\nexport { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';\n\nexport {\n ConsoleSpanExporter,\n RandomIdGenerator,\n InMemorySpanExporter,\n NoopSpanProcessor,\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n SamplingDecision,\n} from '@opentelemetry/sdk-trace';\nexport type {\n ReadableSpan,\n SpanExporter,\n Sampler,\n SamplingResult,\n Span,\n SpanProcessor,\n TimedEvent,\n SpanLimits,\n IdGenerator,\n} from '@opentelemetry/sdk-trace';\n"]}
import type { SpanExporter } from '@opentelemetry/sdk-trace';
import { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';
/**
* A SimpleSpanProcessor with the old constructor call signature that
* takes just a single exporter argument. This version does not support
* the additional options that the SimpleSpanProcessor in sdk-trace does.
*/
export declare class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {
constructor(exporter: SpanExporter);
}
//# sourceMappingURL=SimpleSpanProcessor-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';
/**
* A SimpleSpanProcessor with the old constructor call signature that
* takes just a single exporter argument. This version does not support
* the additional options that the SimpleSpanProcessor in sdk-trace does.
*/
export class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {
constructor(exporter) {
super({ exporter });
}
}
//# sourceMappingURL=SimpleSpanProcessor-shim.js.map
{"version":3,"file":"SimpleSpanProcessor-shim.js","sourceRoot":"","sources":["../../src/SimpleSpanProcessor-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,mBAAmB,IAAI,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAE9F;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,2BAA2B;IAClE,YAAY,QAAsB;QAChC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;IACtB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from '@opentelemetry/sdk-trace';\nimport { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';\n\n/**\n * A SimpleSpanProcessor with the old constructor call signature that\n * takes just a single exporter argument. This version does not support\n * the additional options that the SimpleSpanProcessor in sdk-trace does.\n */\nexport class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {\n constructor(exporter: SpanExporter) {\n super({ exporter });\n }\n}\n"]}
import type { ContextManager, TextMapPropagator } from '@opentelemetry/api';
import type { TracerProviderOptions } from '@opentelemetry/sdk-trace';
/**
* TracerConfig provides an interface for configuring a BasicTracerProvider.
*/
export interface TracerConfig extends TracerProviderOptions {
/** General Limits */
generalLimits?: GeneralLimits;
}
/** Global configuration limits of trace service */
export interface GeneralLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per trace */
attributeCountLimit?: number;
}
/**
* Configuration options for registering the API with the SDK.
* Undefined values may be substituted for defaults, and null
* values will not be registered.
*/
export interface SDKRegistrationConfig {
/** Propagator to register as the global propagator */
propagator?: TextMapPropagator | null;
/** Context manager to register as the global context manager */
contextManager?: ContextManager | null;
}
/** Interface configuration for a buffer. */
export interface BufferConfig {
/** The maximum batch size of every export. It must be smaller or equal to
* maxQueueSize. The default value is 512. */
maxExportBatchSize?: number;
/** The delay interval in milliseconds between two consecutive exports.
* The default value is 5000ms. */
scheduledDelayMillis?: number;
/** How long the export can run before it is cancelled.
* The default value is 30000ms */
exportTimeoutMillis?: number;
/** The maximum queue size. After the size is reached spans are dropped.
* The default value is 2048. */
maxQueueSize?: number;
}
/** Interface configuration for BatchSpanProcessor on browser */
export interface BatchSpanProcessorBrowserConfig extends BufferConfig {
/** Disable flush when a user navigates to a new page, closes the tab or the browser, or,
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}
//# sourceMappingURL=types-shim.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=types-shim.js.map
{"version":3,"file":"types-shim.js","sourceRoot":"","sources":["../../src/types-shim.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ContextManager, TextMapPropagator } from '@opentelemetry/api';\nimport type { TracerProviderOptions } from '@opentelemetry/sdk-trace';\n\n/**\n * TracerConfig provides an interface for configuring a BasicTracerProvider.\n */\nexport interface TracerConfig extends TracerProviderOptions {\n /** General Limits */\n generalLimits?: GeneralLimits;\n}\n\n/** Global configuration limits of trace service */\nexport interface GeneralLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per trace */\n attributeCountLimit?: number;\n}\n\n/**\n * Configuration options for registering the API with the SDK.\n * Undefined values may be substituted for defaults, and null\n * values will not be registered.\n */\nexport interface SDKRegistrationConfig {\n /** Propagator to register as the global propagator */\n propagator?: TextMapPropagator | null;\n\n /** Context manager to register as the global context manager */\n contextManager?: ContextManager | null;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached spans are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\n/** Interface configuration for BatchSpanProcessor on browser */\nexport interface BatchSpanProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n"]}
import type { TracerConfig } from './types-shim';
import { TracerProvider } from '@opentelemetry/sdk-trace';
/**
* A TracerProvider implementation that reads configuration defaults from
* OTEL_* environment variables per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export declare class BasicTracerProvider extends TracerProvider {
constructor(config?: TracerConfig);
}
//# sourceMappingURL=BasicTracerProvider-shim.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasicTracerProvider = void 0;
const core_1 = require("@opentelemetry/core");
const config_1 = require("./config");
const utility_1 = require("./utility");
const sdk_trace_1 = require("@opentelemetry/sdk-trace");
/**
* A TracerProvider implementation that reads configuration defaults from
* OTEL_* environment variables per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
class BasicTracerProvider extends sdk_trace_1.TracerProvider {
constructor(config = {}) {
const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config));
delete mergedConfig.generalLimits;
super(mergedConfig);
}
}
exports.BasicTracerProvider = BasicTracerProvider;
//# sourceMappingURL=BasicTracerProvider-shim.js.map
{"version":3,"file":"BasicTracerProvider-shim.js","sourceRoot":"","sources":["../../src/BasicTracerProvider-shim.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,8CAA4C;AAC5C,qCAA6C;AAE7C,uCAA8C;AAC9C,wDAA0D;AAE1D;;;;GAIG;AACH,MAAa,mBAAoB,SAAQ,0BAAc;IACrD,YAAY,SAAuB,EAAE;QACnC,MAAM,YAAY,GAAG,IAAA,YAAK,EACxB,EAAE,EACF,IAAA,0BAAiB,GAAE,EACnB,IAAA,2BAAiB,EAAC,MAAM,CAAC,CAC1B,CAAC;QACF,OAAO,YAAY,CAAC,aAAa,CAAC;QAClC,KAAK,CAAC,YAAY,CAAC,CAAC;IACtB,CAAC;CACF;AAVD,kDAUC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { merge } from '@opentelemetry/core';\nimport { loadDefaultConfig } from './config';\nimport type { TracerConfig } from './types-shim';\nimport { reconfigureLimits } from './utility';\nimport { TracerProvider } from '@opentelemetry/sdk-trace';\n\n/**\n * A TracerProvider implementation that reads configuration defaults from\n * OTEL_* environment variables per\n * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/\n */\nexport class BasicTracerProvider extends TracerProvider {\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n delete mergedConfig.generalLimits;\n super(mergedConfig);\n }\n}\n"]}
import type { SpanExporter } from '@opentelemetry/sdk-trace';
import { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';
import type { BatchSpanProcessorBrowserConfig, BufferConfig } from './types-shim';
/**
* A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
export declare class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {
constructor(exporter: SpanExporter, config?: BufferConfig | BatchSpanProcessorBrowserConfig);
}
//# sourceMappingURL=BatchSpanProcessor-shim.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchSpanProcessor = void 0;
const core_1 = require("@opentelemetry/core");
const sdk_trace_1 = require("@opentelemetry/sdk-trace");
/**
* A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per
* https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
*/
class BatchSpanProcessor extends sdk_trace_1.BatchSpanProcessor {
constructor(exporter, config) {
if (!config) {
config = {};
}
const envFallbacks = [
['maxExportBatchSize', 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE'],
['maxQueueSize', 'OTEL_BSP_MAX_QUEUE_SIZE'],
['scheduledDelayMillis', 'OTEL_BSP_SCHEDULE_DELAY'],
['exportTimeoutMillis', 'OTEL_BSP_EXPORT_TIMEOUT'],
];
for (const [configName, envName] of envFallbacks) {
if (config[configName] === undefined) {
const envFallback = (0, core_1.getNumberFromEnv)(envName);
if (envFallback !== undefined) {
config[configName] = envFallback;
}
}
}
super({ exporter, ...config });
}
}
exports.BatchSpanProcessor = BatchSpanProcessor;
//# sourceMappingURL=BatchSpanProcessor-shim.js.map
{"version":3,"file":"BatchSpanProcessor-shim.js","sourceRoot":"","sources":["../../src/BatchSpanProcessor-shim.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,8CAAuD;AAEvD,wDAA6F;AAM7F;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,8BAA2B;IACjE,YACE,QAAsB,EACtB,MAAuD;QAEvD,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,GAAG,EAAE,CAAC;SACb;QACD,MAAM,YAAY,GAAmC;YACnD,CAAC,oBAAoB,EAAE,gCAAgC,CAAC;YACxD,CAAC,cAAc,EAAE,yBAAyB,CAAC;YAC3C,CAAC,sBAAsB,EAAE,yBAAyB,CAAC;YACnD,CAAC,qBAAqB,EAAE,yBAAyB,CAAC;SACnD,CAAC;QACF,KAAK,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,YAAY,EAAE;YAChD,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,SAAS,EAAE;gBACpC,MAAM,WAAW,GAAG,IAAA,uBAAgB,EAAC,OAAO,CAAC,CAAC;gBAC9C,IAAI,WAAW,KAAK,SAAS,EAAE;oBAC7B,MAAM,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;iBAClC;aACF;SACF;QAED,KAAK,CAAC,EAAE,QAAQ,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACjC,CAAC;CACF;AAzBD,gDAyBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getNumberFromEnv } from '@opentelemetry/core';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace';\nimport { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';\nimport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n} from './types-shim';\n\n/**\n * A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per\n * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/\n */\nexport class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {\n constructor(\n exporter: SpanExporter,\n config?: BufferConfig | BatchSpanProcessorBrowserConfig\n ) {\n if (!config) {\n config = {};\n }\n const envFallbacks: [keyof BufferConfig, string][] = [\n ['maxExportBatchSize', 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE'],\n ['maxQueueSize', 'OTEL_BSP_MAX_QUEUE_SIZE'],\n ['scheduledDelayMillis', 'OTEL_BSP_SCHEDULE_DELAY'],\n ['exportTimeoutMillis', 'OTEL_BSP_EXPORT_TIMEOUT'],\n ];\n for (const [configName, envName] of envFallbacks) {\n if (config[configName] === undefined) {\n const envFallback = getNumberFromEnv(envName);\n if (envFallback !== undefined) {\n config[configName] = envFallback;\n }\n }\n }\n\n super({ exporter, ...config });\n }\n}\n"]}
export { BasicTracerProvider } from './BasicTracerProvider-shim';
export type { BufferConfig, BatchSpanProcessorBrowserConfig, GeneralLimits, TracerConfig, SDKRegistrationConfig, } from './types-shim';
export { BatchSpanProcessor } from './BatchSpanProcessor-shim';
export { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';
export { ConsoleSpanExporter, RandomIdGenerator, InMemorySpanExporter, NoopSpanProcessor, AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler, SamplingDecision, } from '@opentelemetry/sdk-trace';
export type { ReadableSpan, SpanExporter, Sampler, SamplingResult, Span, SpanProcessor, TimedEvent, SpanLimits, IdGenerator, } from '@opentelemetry/sdk-trace';
//# sourceMappingURL=index-shim.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.InMemorySpanExporter = exports.RandomIdGenerator = exports.ConsoleSpanExporter = exports.SimpleSpanProcessor = exports.BatchSpanProcessor = exports.BasicTracerProvider = void 0;
var BasicTracerProvider_shim_1 = require("./BasicTracerProvider-shim");
Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: function () { return BasicTracerProvider_shim_1.BasicTracerProvider; } });
var BatchSpanProcessor_shim_1 = require("./BatchSpanProcessor-shim");
Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return BatchSpanProcessor_shim_1.BatchSpanProcessor; } });
var SimpleSpanProcessor_shim_1 = require("./SimpleSpanProcessor-shim");
Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: function () { return SimpleSpanProcessor_shim_1.SimpleSpanProcessor; } });
var sdk_trace_1 = require("@opentelemetry/sdk-trace");
Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: function () { return sdk_trace_1.ConsoleSpanExporter; } });
Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return sdk_trace_1.RandomIdGenerator; } });
Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: function () { return sdk_trace_1.InMemorySpanExporter; } });
Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: function () { return sdk_trace_1.NoopSpanProcessor; } });
Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: function () { return sdk_trace_1.AlwaysOffSampler; } });
Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: function () { return sdk_trace_1.AlwaysOnSampler; } });
Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: function () { return sdk_trace_1.ParentBasedSampler; } });
Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: function () { return sdk_trace_1.TraceIdRatioBasedSampler; } });
Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return sdk_trace_1.SamplingDecision; } });
//# sourceMappingURL=index-shim.js.map
{"version":3,"file":"index-shim.js","sourceRoot":"","sources":["../../src/index-shim.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,uEAAiE;AAAxD,+HAAA,mBAAmB,OAAA;AAQ5B,qEAA+D;AAAtD,6HAAA,kBAAkB,OAAA;AAC3B,uEAAiE;AAAxD,+HAAA,mBAAmB,OAAA;AAE5B,sDAUkC;AAThC,gHAAA,mBAAmB,OAAA;AACnB,8GAAA,iBAAiB,OAAA;AACjB,iHAAA,oBAAoB,OAAA;AACpB,8GAAA,iBAAiB,OAAA;AACjB,6GAAA,gBAAgB,OAAA;AAChB,4GAAA,eAAe,OAAA;AACf,+GAAA,kBAAkB,OAAA;AAClB,qHAAA,wBAAwB,OAAA;AACxB,6GAAA,gBAAgB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BasicTracerProvider } from './BasicTracerProvider-shim';\nexport type {\n BufferConfig,\n BatchSpanProcessorBrowserConfig,\n GeneralLimits,\n TracerConfig,\n SDKRegistrationConfig,\n} from './types-shim';\nexport { BatchSpanProcessor } from './BatchSpanProcessor-shim';\nexport { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';\n\nexport {\n ConsoleSpanExporter,\n RandomIdGenerator,\n InMemorySpanExporter,\n NoopSpanProcessor,\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n SamplingDecision,\n} from '@opentelemetry/sdk-trace';\nexport type {\n ReadableSpan,\n SpanExporter,\n Sampler,\n SamplingResult,\n Span,\n SpanProcessor,\n TimedEvent,\n SpanLimits,\n IdGenerator,\n} from '@opentelemetry/sdk-trace';\n"]}
import type { SpanExporter } from '@opentelemetry/sdk-trace';
import { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';
/**
* A SimpleSpanProcessor with the old constructor call signature that
* takes just a single exporter argument. This version does not support
* the additional options that the SimpleSpanProcessor in sdk-trace does.
*/
export declare class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {
constructor(exporter: SpanExporter);
}
//# sourceMappingURL=SimpleSpanProcessor-shim.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleSpanProcessor = void 0;
const sdk_trace_1 = require("@opentelemetry/sdk-trace");
/**
* A SimpleSpanProcessor with the old constructor call signature that
* takes just a single exporter argument. This version does not support
* the additional options that the SimpleSpanProcessor in sdk-trace does.
*/
class SimpleSpanProcessor extends sdk_trace_1.SimpleSpanProcessor {
constructor(exporter) {
super({ exporter });
}
}
exports.SimpleSpanProcessor = SimpleSpanProcessor;
//# sourceMappingURL=SimpleSpanProcessor-shim.js.map
{"version":3,"file":"SimpleSpanProcessor-shim.js","sourceRoot":"","sources":["../../src/SimpleSpanProcessor-shim.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,wDAA8F;AAE9F;;;;GAIG;AACH,MAAa,mBAAoB,SAAQ,+BAA2B;IAClE,YAAY,QAAsB;QAChC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;IACtB,CAAC;CACF;AAJD,kDAIC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from '@opentelemetry/sdk-trace';\nimport { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';\n\n/**\n * A SimpleSpanProcessor with the old constructor call signature that\n * takes just a single exporter argument. This version does not support\n * the additional options that the SimpleSpanProcessor in sdk-trace does.\n */\nexport class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {\n constructor(exporter: SpanExporter) {\n super({ exporter });\n }\n}\n"]}
import type { ContextManager, TextMapPropagator } from '@opentelemetry/api';
import type { TracerProviderOptions } from '@opentelemetry/sdk-trace';
/**
* TracerConfig provides an interface for configuring a BasicTracerProvider.
*/
export interface TracerConfig extends TracerProviderOptions {
/** General Limits */
generalLimits?: GeneralLimits;
}
/** Global configuration limits of trace service */
export interface GeneralLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per trace */
attributeCountLimit?: number;
}
/**
* Configuration options for registering the API with the SDK.
* Undefined values may be substituted for defaults, and null
* values will not be registered.
*/
export interface SDKRegistrationConfig {
/** Propagator to register as the global propagator */
propagator?: TextMapPropagator | null;
/** Context manager to register as the global context manager */
contextManager?: ContextManager | null;
}
/** Interface configuration for a buffer. */
export interface BufferConfig {
/** The maximum batch size of every export. It must be smaller or equal to
* maxQueueSize. The default value is 512. */
maxExportBatchSize?: number;
/** The delay interval in milliseconds between two consecutive exports.
* The default value is 5000ms. */
scheduledDelayMillis?: number;
/** How long the export can run before it is cancelled.
* The default value is 30000ms */
exportTimeoutMillis?: number;
/** The maximum queue size. After the size is reached spans are dropped.
* The default value is 2048. */
maxQueueSize?: number;
}
/** Interface configuration for BatchSpanProcessor on browser */
export interface BatchSpanProcessorBrowserConfig extends BufferConfig {
/** Disable flush when a user navigates to a new page, closes the tab or the browser, or,
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}
//# sourceMappingURL=types-shim.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types-shim.js.map
{"version":3,"file":"types-shim.js","sourceRoot":"","sources":["../../src/types-shim.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ContextManager, TextMapPropagator } from '@opentelemetry/api';\nimport type { TracerProviderOptions } from '@opentelemetry/sdk-trace';\n\n/**\n * TracerConfig provides an interface for configuring a BasicTracerProvider.\n */\nexport interface TracerConfig extends TracerProviderOptions {\n /** General Limits */\n generalLimits?: GeneralLimits;\n}\n\n/** Global configuration limits of trace service */\nexport interface GeneralLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per trace */\n attributeCountLimit?: number;\n}\n\n/**\n * Configuration options for registering the API with the SDK.\n * Undefined values may be substituted for defaults, and null\n * values will not be registered.\n */\nexport interface SDKRegistrationConfig {\n /** Propagator to register as the global propagator */\n propagator?: TextMapPropagator | null;\n\n /** Context manager to register as the global context manager */\n contextManager?: ContextManager | null;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached spans are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\n/** Interface configuration for BatchSpanProcessor on browser */\nexport interface BatchSpanProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n"]}
+1
-1

@@ -1,2 +0,2 @@

import type { Sampler } from './Sampler';
import type { Sampler } from '@opentelemetry/sdk-trace';
/**

@@ -3,0 +3,0 @@ * Load default configuration. For fields with primitive values, any user-provided

@@ -7,6 +7,3 @@ /*

import { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';
import { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
import { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
import { ParentBasedSampler } from './sampler/ParentBasedSampler';
import { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
import { AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler, } from '@opentelemetry/sdk-trace';
var TracesSamplerValues;

@@ -13,0 +10,0 @@ (function (TracesSamplerValues) {

@@ -1,1 +0,1 @@

{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAE9E,IAAW,mBAOV;AAPD,WAAW,mBAAmB;IAC5B,+CAAwB,CAAA;IACxB,6CAAsB,CAAA;IACtB,sEAA+C,CAAA;IAC/C,oEAA6C,CAAA;IAC7C,2EAAoD,CAAA;IACpD,oDAA6B,CAAA;AAC/B,CAAC,EAPU,mBAAmB,KAAnB,mBAAmB,QAO7B;AAED,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB;;;;;GAKG;AAEH,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,UAAU,iBAAiB;IAC/B,OAAO;QACL,OAAO,EAAE,mBAAmB,EAAE;QAC9B,uBAAuB,EAAE,KAAK;QAC9B,aAAa,EAAE;YACb,yBAAyB,EACvB,gBAAgB,CAAC,mCAAmC,CAAC,IAAI,QAAQ;YACnE,mBAAmB,EACjB,gBAAgB,CAAC,4BAA4B,CAAC,IAAI,GAAG;SACxD;QACD,UAAU,EAAE;YACV,yBAAyB,EACvB,gBAAgB,CAAC,wCAAwC,CAAC,IAAI,QAAQ;YACxE,mBAAmB,EACjB,gBAAgB,C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AE,IAAI,eAAe,EAAE;aAC5B,CAAC,CAAC;KACN;AACH,CAAC;AAED,SAAS,4BAA4B;IACnC,MAAM,WAAW,GAAG,gBAAgB,CAAC,yBAAyB,CAAC,CAAC;IAChE,IAAI,WAAW,IAAI,IAAI,EAAE;QACvB,IAAI,CAAC,KAAK,CACR,mDAAmD,aAAa,GAAG,CACpE,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,IAAI,WAAW,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,EAAE;QACtC,IAAI,CAAC,KAAK,CACR,2BAA2B,WAAW,8DAA8D,aAAa,GAAG,CACrH,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n"]}
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEzE,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,0BAA0B,CAAC;AAElC,IAAW,mBAOV;AAPD,WAAW,mBAAmB;IAC5B,+CAAwB,CAAA;IACxB,6CAAsB,CAAA;IACtB,sEAA+C,CAAA;IAC/C,oEAA6C,CAAA;IAC7C,2EAAoD,CAAA;IACpD,oDAA6B,CAAA;AAC/B,CAAC,EAPU,mBAAmB,KAAnB,mBAAmB,QAO7B;AAED,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB;;;;;GAKG;AAEH,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,UAAU,iBAAiB;IAC/B,OAAO;QACL,OAAO,EAAE,mBAAmB,EAAE;QAC9B,uBAAuB,EAAE,KAAK;QAC9B,aAAa,EAAE;YACb,yBAAyB,EACvB,gBAAgB,CAAC,mCAAmC,CAAC,IAAI,QAAQ;YACnE,mBAAmB,EACjB,g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C,CAAC;QACL;YACE,IAAI,CAAC,KAAK,CACR,8BAA8B,OAAO,6BAA6B,mBAAmB,CAAC,mBAAmB,IAAI,CAC9G,CAAC;YACF,OAAO,IAAI,kBAAkB,CAAC;gBAC5B,IAAI,EAAE,IAAI,eAAe,EAAE;aAC5B,CAAC,CAAC;KACN;AACH,CAAC;AAED,SAAS,4BAA4B;IACnC,MAAM,WAAW,GAAG,gBAAgB,CAAC,yBAAyB,CAAC,CAAC;IAChE,IAAI,WAAW,IAAI,IAAI,EAAE;QACvB,IAAI,CAAC,KAAK,CACR,mDAAmD,aAAa,GAAG,CACpE,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,IAAI,WAAW,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,EAAE;QACtC,IAAI,CAAC,KAAK,CACR,2BAA2B,WAAW,8DAA8D,aAAa,GAAG,CACrH,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from '@opentelemetry/sdk-trace';\nimport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n"]}

@@ -1,15 +0,5 @@

import type { Sampler } from './Sampler';
import type { SpanLimits, TracerConfig, GeneralLimits } from './types';
import type { TracerConfig } from './types-shim';
export declare const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;
export declare const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT: number;
/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
export declare function mergeConfig(userConfig: TracerConfig): TracerConfig & {
sampler: Sampler;
spanLimits: SpanLimits;
generalLimits: GeneralLimits;
};
/**
* When general limits are provided and model specific limits are not,

@@ -16,0 +6,0 @@ * configures the model specific limits by using the values from the general ones.

@@ -5,3 +5,2 @@ /*

*/
import { buildSamplerFromEnv, loadDefaultConfig } from './config';
import { getNumberFromEnv } from '@opentelemetry/core';

@@ -11,16 +10,2 @@ export const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;

/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
export function mergeConfig(userConfig) {
const perInstanceDefaults = {
sampler: buildSamplerFromEnv(),
};
const DEFAULT_CONFIG = loadDefaultConfig();
const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
return target;
}
/**
* When general limits are provided and model specific limits are not,

@@ -27,0 +12,0 @@ * configures the model specific limits by using the values from the general ones.

@@ -1,1 +0,1 @@

{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAGlE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AACjD,MAAM,CAAC,MAAM,oCAAoC,GAAG,QAAQ,CAAC;AAE7D;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,UAAwB;IAKlD,MAAM,mBAAmB,GAA0B;QACjD,OAAO,EAAE,mBAAmB,EAAE;KAC/B,CAAC;IAEF,MAAM,cAAc,GAAG,iBAAiB,EAAE,CAAC;IAE3C,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAC1B,EAAE,EACF,cAAc,EACd,mBAAmB,EACnB,UAAU,CACX,CAAC;IAEF,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,MAAM,CAClC,EAAE,EACF,cAAc,CAAC,aAAa,EAC5B,UAAU,CAAC,aAAa,IAAI,EAAE,CAC/B,CAAC;IAEF,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAC/B,EAAE,EACF,cAAc,CAAC,UAAU,EACzB,UAAU,CAAC,UAAU,IAAI,EAAE,CAC5B,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAwB;IACxD,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAE5D;;OAEG;IACH,UAAU,CAAC,mBAAmB;QAC5B,UAAU,CAAC,UAAU,EAAE,mBAAmB;YAC1C,UAAU,CAAC,aAAa,EAAE,mBAAmB;YAC7C,gBAAgB,CAAC,iCAAiC,CAAC;YACnD,gBAAgB,CAAC,4BAA4B,CAAC;YAC9C,6BAA6B,CAAC;IAEhC;;OAEG;IACH,UAAU,CAAC,yBAAyB;QAClC,UAAU,CAAC,UAAU,EAAE,yBAAyB;YAChD,UAAU,CAAC,aAAa,EAAE,yBAAyB;YACnD,gBAAgB,CAAC,wCAAwC,CAAC;YAC1D,gBAAgB,CAAC,mCAAmC,CAAC;YACrD,oCAAoC,CAAC;IAEvC,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport type { Sampler } from './Sampler';\nimport type { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n"]}
{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AACjD,MAAM,CAAC,MAAM,oCAAoC,GAAG,QAAQ,CAAC;AAE7D;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAwB;IACxD,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAE5D;;OAEG;IACH,UAAU,CAAC,mBAAmB;QAC5B,UAAU,CAAC,UAAU,EAAE,mBAAmB;YAC1C,UAAU,CAAC,aAAa,EAAE,mBAAmB;YAC7C,gBAAgB,CAAC,iCAAiC,CAAC;YACnD,gBAAgB,CAAC,4BAA4B,CAAC;YAC9C,6BAA6B,CAAC;IAEhC;;OAEG;IACH,UAAU,CAAC,yBAAyB;QAClC,UAAU,CAAC,UAAU,EAAE,yBAAyB;YAChD,UAAU,CAAC,aAAa,EAAE,yBAAyB;YACnD,gBAAgB,CAAC,wCAAwC,CAAC;YAC1D,gBAAgB,CAAC,mCAAmC,CAAC;YACrD,oCAAoC,CAAC;IAEvC,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerConfig } from './types-shim';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n"]}

@@ -1,2 +0,2 @@

export declare const VERSION = "2.8.0";
export declare const VERSION = "2.9.0";
//# sourceMappingURL=version.d.ts.map

@@ -6,3 +6,3 @@ /*

// this is autogenerated file, see scripts/version-update.js
export const VERSION = '2.8.0';
export const VERSION = '2.9.0';
//# sourceMappingURL=version.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.8.0';\n"]}
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.9.0';\n"]}

@@ -1,2 +0,2 @@

import type { Sampler } from './Sampler';
import type { Sampler } from '@opentelemetry/sdk-trace';
/**

@@ -3,0 +3,0 @@ * Load default configuration. For fields with primitive values, any user-provided

@@ -7,6 +7,3 @@ /*

import { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';
import { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
import { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
import { ParentBasedSampler } from './sampler/ParentBasedSampler';
import { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
import { AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler, } from '@opentelemetry/sdk-trace';
var TracesSamplerValues;

@@ -13,0 +10,0 @@ (function (TracesSamplerValues) {

@@ -1,1 +0,1 @@

{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAE9E,IAAW,mBAOV;AAPD,WAAW,mBAAmB;IAC5B,+CAAwB,CAAA;IACxB,6CAAsB,CAAA;IACtB,sEAA+C,CAAA;IAC/C,oEAA6C,CAAA;IAC7C,2EAAoD,CAAA;IACpD,oDAA6B,CAAA;AAC/B,CAAC,EAPU,mBAAmB,KAAnB,mBAAmB,QAO7B;AAED,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB;;;;;GAKG;AAEH,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,UAAU,iBAAiB;IAC/B,OAAO;QACL,OAAO,EAAE,mBAAmB,EAAE;QAC9B,uBAAuB,EAAE,KAAK;QAC9B,aAAa,EAAE;YACb,yBAAyB,EACvB,gBAAgB,CAAC,mCAAmC,CAAC,IAAI,QAAQ;YACnE,mBAAmB,EACjB,gBAAgB,CAAC,4BAA4B,CAAC,IAAI,GAAG;SACxD;QACD,UAAU,EAAE;YACV,yBAAyB,EACvB,gBAAgB,CAAC,wCAAwC,C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YACF,OAAO,IAAI,kBAAkB,CAAC;gBAC5B,IAAI,EAAE,IAAI,eAAe,EAAE;aAC5B,CAAC,CAAC;KACN;AACH,CAAC;AAED,SAAS,4BAA4B;IACnC,MAAM,WAAW,GAAG,gBAAgB,CAAC,yBAAyB,CAAC,CAAC;IAChE,IAAI,WAAW,IAAI,IAAI,EAAE;QACvB,IAAI,CAAC,KAAK,CACR,mDAAmD,aAAa,GAAG,CACpE,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,IAAI,WAAW,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,EAAE;QACtC,IAAI,CAAC,KAAK,CACR,2BAA2B,WAAW,8DAA8D,aAAa,GAAG,CACrH,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n"]}
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEzE,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,0BAA0B,CAAC;AAElC,IAAW,mBAOV;AAPD,WAAW,mBAAmB;IAC5B,+CAAwB,CAAA;IACxB,6CAAsB,CAAA;IACtB,sEAA+C,CAAA;IAC/C,oEAA6C,CAAA;IAC7C,2EAAoD,CAAA;IACpD,oDAA6B,CAAA;AAC/B,CAAC,EAPU,mBAAmB,KAAnB,mBAAmB,QAO7B;AAED,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB;;;;;GAKG;AAEH,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,UAAU,iBAAiB;IAC/B,OAAO;QACL,OAAO,EAAE,mBAAmB,EAAE;QAC9B,uBAAuB,EAAE,KAAK;QAC9B,aAAa,EAAE;YACb,yBAAyB,EACvB,gBAAgB,CAAC,m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AI,wBAAwB,CAAC,4BAA4B,EAAE,CAAC;aACnE,CAAC,CAAC;QACL;YACE,IAAI,CAAC,KAAK,CACR,8BAA8B,OAAO,6BAA6B,mBAAmB,CAAC,mBAAmB,IAAI,CAC9G,CAAC;YACF,OAAO,IAAI,kBAAkB,CAAC;gBAC5B,IAAI,EAAE,IAAI,eAAe,EAAE;aAC5B,CAAC,CAAC;KACN;AACH,CAAC;AAED,SAAS,4BAA4B;IACnC,MAAM,WAAW,GAAG,gBAAgB,CAAC,yBAAyB,CAAC,CAAC;IAChE,IAAI,WAAW,IAAI,IAAI,EAAE;QACvB,IAAI,CAAC,KAAK,CACR,mDAAmD,aAAa,GAAG,CACpE,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,IAAI,WAAW,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,EAAE;QACtC,IAAI,CAAC,KAAK,CACR,2BAA2B,WAAW,8DAA8D,aAAa,GAAG,CACrH,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from '@opentelemetry/sdk-trace';\nimport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n"]}

@@ -1,15 +0,5 @@

import type { Sampler } from './Sampler';
import type { SpanLimits, TracerConfig, GeneralLimits } from './types';
import type { TracerConfig } from './types-shim';
export declare const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;
export declare const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT: number;
/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
export declare function mergeConfig(userConfig: TracerConfig): TracerConfig & {
sampler: Sampler;
spanLimits: SpanLimits;
generalLimits: GeneralLimits;
};
/**
* When general limits are provided and model specific limits are not,

@@ -16,0 +6,0 @@ * configures the model specific limits by using the values from the general ones.

@@ -5,3 +5,2 @@ /*

*/
import { buildSamplerFromEnv, loadDefaultConfig } from './config';
import { getNumberFromEnv } from '@opentelemetry/core';

@@ -11,16 +10,2 @@ export const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;

/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
export function mergeConfig(userConfig) {
const perInstanceDefaults = {
sampler: buildSamplerFromEnv(),
};
const DEFAULT_CONFIG = loadDefaultConfig();
const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
return target;
}
/**
* When general limits are provided and model specific limits are not,

@@ -27,0 +12,0 @@ * configures the model specific limits by using the values from the general ones.

@@ -1,1 +0,1 @@

{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAGlE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AACjD,MAAM,CAAC,MAAM,oCAAoC,GAAG,QAAQ,CAAC;AAE7D;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,UAAwB;IAKlD,MAAM,mBAAmB,GAA0B;QACjD,OAAO,EAAE,mBAAmB,EAAE;KAC/B,CAAC;IAEF,MAAM,cAAc,GAAG,iBAAiB,EAAE,CAAC;IAE3C,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAC1B,EAAE,EACF,cAAc,EACd,mBAAmB,EACnB,UAAU,CACX,CAAC;IAEF,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,MAAM,CAClC,EAAE,EACF,cAAc,CAAC,aAAa,EAC5B,UAAU,CAAC,aAAa,IAAI,EAAE,CAC/B,CAAC;IAEF,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAC/B,EAAE,EACF,cAAc,CAAC,UAAU,EACzB,UAAU,CAAC,UAAU,IAAI,EAAE,CAC5B,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAwB;IACxD,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAE5D;;OAEG;IACH,UAAU,CAAC,mBAAmB;QAC5B,UAAU,CAAC,UAAU,EAAE,mBAAmB;YAC1C,UAAU,CAAC,aAAa,EAAE,mBAAmB;YAC7C,gBAAgB,CAAC,iCAAiC,CAAC;YACnD,gBAAgB,CAAC,4BAA4B,CAAC;YAC9C,6BAA6B,CAAC;IAEhC;;OAEG;IACH,UAAU,CAAC,yBAAyB;QAClC,UAAU,CAAC,UAAU,EAAE,yBAAyB;YAChD,UAAU,CAAC,aAAa,EAAE,yBAAyB;YACnD,gBAAgB,CAAC,wCAAwC,CAAC;YAC1D,gBAAgB,CAAC,mCAAmC,CAAC;YACrD,oCAAoC,CAAC;IAEvC,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport type { Sampler } from './Sampler';\nimport type { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n"]}
{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AACjD,MAAM,CAAC,MAAM,oCAAoC,GAAG,QAAQ,CAAC;AAE7D;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAwB;IACxD,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAE5D;;OAEG;IACH,UAAU,CAAC,mBAAmB;QAC5B,UAAU,CAAC,UAAU,EAAE,mBAAmB;YAC1C,UAAU,CAAC,aAAa,EAAE,mBAAmB;YAC7C,gBAAgB,CAAC,iCAAiC,CAAC;YACnD,gBAAgB,CAAC,4BAA4B,CAAC;YAC9C,6BAA6B,CAAC;IAEhC;;OAEG;IACH,UAAU,CAAC,yBAAyB;QAClC,UAAU,CAAC,UAAU,EAAE,yBAAyB;YAChD,UAAU,CAAC,aAAa,EAAE,yBAAyB;YACnD,gBAAgB,CAAC,wCAAwC,CAAC;YAC1D,gBAAgB,CAAC,mCAAmC,CAAC;YACrD,oCAAoC,CAAC;IAEvC,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerConfig } from './types-shim';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n"]}

@@ -1,2 +0,2 @@

export declare const VERSION = "2.8.0";
export declare const VERSION = "2.9.0";
//# sourceMappingURL=version.d.ts.map

@@ -6,3 +6,3 @@ /*

// this is autogenerated file, see scripts/version-update.js
export const VERSION = '2.8.0';
export const VERSION = '2.9.0';
//# sourceMappingURL=version.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.8.0';\n"]}
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.9.0';\n"]}

@@ -1,2 +0,2 @@

import type { Sampler } from './Sampler';
import type { Sampler } from '@opentelemetry/sdk-trace';
/**

@@ -3,0 +3,0 @@ * Load default configuration. For fields with primitive values, any user-provided

@@ -10,6 +10,3 @@ "use strict";

const core_1 = require("@opentelemetry/core");
const AlwaysOffSampler_1 = require("./sampler/AlwaysOffSampler");
const AlwaysOnSampler_1 = require("./sampler/AlwaysOnSampler");
const ParentBasedSampler_1 = require("./sampler/ParentBasedSampler");
const TraceIdRatioBasedSampler_1 = require("./sampler/TraceIdRatioBasedSampler");
const sdk_trace_1 = require("@opentelemetry/sdk-trace");
var TracesSamplerValues;

@@ -60,23 +57,23 @@ (function (TracesSamplerValues) {

case TracesSamplerValues.AlwaysOn:
return new AlwaysOnSampler_1.AlwaysOnSampler();
return new sdk_trace_1.AlwaysOnSampler();
case TracesSamplerValues.AlwaysOff:
return new AlwaysOffSampler_1.AlwaysOffSampler();
return new sdk_trace_1.AlwaysOffSampler();
case TracesSamplerValues.ParentBasedAlwaysOn:
return new ParentBasedSampler_1.ParentBasedSampler({
root: new AlwaysOnSampler_1.AlwaysOnSampler(),
return new sdk_trace_1.ParentBasedSampler({
root: new sdk_trace_1.AlwaysOnSampler(),
});
case TracesSamplerValues.ParentBasedAlwaysOff:
return new ParentBasedSampler_1.ParentBasedSampler({
root: new AlwaysOffSampler_1.AlwaysOffSampler(),
return new sdk_trace_1.ParentBasedSampler({
root: new sdk_trace_1.AlwaysOffSampler(),
});
case TracesSamplerValues.TraceIdRatio:
return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
return new sdk_trace_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
case TracesSamplerValues.ParentBasedTraceIdRatio:
return new ParentBasedSampler_1.ParentBasedSampler({
root: new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),
return new sdk_trace_1.ParentBasedSampler({
root: new sdk_trace_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),
});
default:
api_1.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`);
return new ParentBasedSampler_1.ParentBasedSampler({
root: new AlwaysOnSampler_1.AlwaysOnSampler(),
return new sdk_trace_1.ParentBasedSampler({
root: new sdk_trace_1.Always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WAAW,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,EAAE;QACtC,UAAI,CAAC,KAAK,CACR,2BAA2B,WAAW,8DAA8D,aAAa,GAAG,CACrH,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n"]}
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4CAA0C;AAC1C,8CAAyE;AAEzE,wDAKkC;AAElC,IAAW,mBAOV;AAPD,WAAW,mBAAmB;IAC5B,+CAAwB,CAAA;IACxB,6CAAsB,CAAA;IACtB,sEAA+C,CAAA;IAC/C,oEAA6C,CAAA;IAC7C,2EAAoD,CAAA;IACpD,oDAA6B,CAAA;AAC/B,CAAC,EAPU,mBAAmB,KAAnB,mBAAmB,QAO7B;AAED,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB;;;;;GAKG;AAEH,+EAA+E;AAC/E,+EAA+E;AAC/E,SAAgB,iBAAiB;IAC/B,OAAO;QACL,OAAO,EAAE,mBAAmB,EAAE;QAC9B,uBAAuB,EAAE,KAAK;QAC9B,aAAa,EAAE;YACb,yBAAyB,EACvB,IAAA,uBAAgB,EAAC,mCAAmC,CAAC,IAAI,QAAQ;YACnE,mBAAmB,EACjB,IAAA,uBAAgB,EAAC,4BAA4B,CAAC,IAAI,GAAG;SACxD;QACD,UAAU,EAAE;YACV,yBAAyB,EACvB,IAAA,uBAAgB,EAAC,wCAAwC,CAAC,IAAI,QAAQ;YACxE,mBAAmB,EACjB,IAAA,uBAAgB,EAAC,iCAAiC,CAAC,IAAI,GAAG;YAC5D,cAAc,EAAE,IAAA,uBAAgB,EAAC,4BAA4B,CAAC,IAAI,GAAG;YACrE,eAAe,EAAE,IAAA,uBAAgB,EAAC,6BAA6B,CAAC,IAAI,GAAG;YACvE,2BAA2B,EACzB,IAAA,uBAAgB,EAAC,2CAA2C,CAAC,IAAI,GAAG;YACtE,0BAA0B,EACxB,IAAA,uBAAg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ACR,mDAAmD,aAAa,GAAG,CACpE,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,IAAI,WAAW,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,EAAE;QACtC,UAAI,CAAC,KAAK,CACR,2BAA2B,WAAW,8DAA8D,aAAa,GAAG,CACrH,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from '@opentelemetry/sdk-trace';\nimport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n"]}

@@ -1,15 +0,5 @@

import type { Sampler } from './Sampler';
import type { SpanLimits, TracerConfig, GeneralLimits } from './types';
import type { TracerConfig } from './types-shim';
export declare const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;
export declare const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT: number;
/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
export declare function mergeConfig(userConfig: TracerConfig): TracerConfig & {
sampler: Sampler;
spanLimits: SpanLimits;
generalLimits: GeneralLimits;
};
/**
* When general limits are provided and model specific limits are not,

@@ -16,0 +6,0 @@ * configures the model specific limits by using the values from the general ones.

@@ -7,4 +7,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.reconfigureLimits = exports.mergeConfig = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = void 0;
const config_1 = require("./config");
exports.reconfigureLimits = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = void 0;
const core_1 = require("@opentelemetry/core");

@@ -14,17 +13,2 @@ exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;

/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
function mergeConfig(userConfig) {
const perInstanceDefaults = {
sampler: (0, config_1.buildSamplerFromEnv)(),
};
const DEFAULT_CONFIG = (0, config_1.loadDefaultConfig)();
const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
return target;
}
exports.mergeConfig = mergeConfig;
/**
* When general limits are provided and model specific limits are not,

@@ -31,0 +15,0 @@ * configures the model specific limits by using the values from the general ones.

@@ -1,1 +0,1 @@

{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,qCAAkE;AAGlE,8CAAuD;AAE1C,QAAA,6BAA6B,GAAG,GAAG,CAAC;AACpC,QAAA,oCAAoC,GAAG,QAAQ,CAAC;AAE7D;;;GAGG;AACH,SAAgB,WAAW,CAAC,UAAwB;IAKlD,MAAM,mBAAmB,GAA0B;QACjD,OAAO,EAAE,IAAA,4BAAmB,GAAE;KAC/B,CAAC;IAEF,MAAM,cAAc,GAAG,IAAA,0BAAiB,GAAE,CAAC;IAE3C,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAC1B,EAAE,EACF,cAAc,EACd,mBAAmB,EACnB,UAAU,CACX,CAAC;IAEF,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,MAAM,CAClC,EAAE,EACF,cAAc,CAAC,aAAa,EAC5B,UAAU,CAAC,aAAa,IAAI,EAAE,CAC/B,CAAC;IAEF,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAC/B,EAAE,EACF,cAAc,CAAC,UAAU,EACzB,UAAU,CAAC,UAAU,IAAI,EAAE,CAC5B,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AA/BD,kCA+BC;AAED;;;;GAIG;AACH,SAAgB,iBAAiB,CAAC,UAAwB;IACxD,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAE5D;;OAEG;IACH,UAAU,CAAC,mBAAmB;QAC5B,UAAU,CAAC,UAAU,EAAE,mBAAmB;YAC1C,UAAU,CAAC,aAAa,EAAE,mBAAmB;YAC7C,IAAA,uBAAgB,EAAC,iCAAiC,CAAC;YACnD,IAAA,uBAAgB,EAAC,4BAA4B,CAAC;YAC9C,qCAA6B,CAAC;IAEhC;;OAEG;IACH,UAAU,CAAC,yBAAyB;QAClC,UAAU,CAAC,UAAU,EAAE,yBAAyB;YAChD,UAAU,CAAC,aAAa,EAAE,yBAAyB;YACnD,IAAA,uBAAgB,EAAC,wCAAwC,CAAC;YAC1D,IAAA,uBAAgB,EAAC,mCAAmC,CAAC;YACrD,4CAAoC,CAAC;IAEvC,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AACvD,CAAC;AAxBD,8CAwBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport type { Sampler } from './Sampler';\nimport type { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n"]}
{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,8CAAuD;AAE1C,QAAA,6BAA6B,GAAG,GAAG,CAAC;AACpC,QAAA,oCAAoC,GAAG,QAAQ,CAAC;AAE7D;;;;GAIG;AACH,SAAgB,iBAAiB,CAAC,UAAwB;IACxD,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAE5D;;OAEG;IACH,UAAU,CAAC,mBAAmB;QAC5B,UAAU,CAAC,UAAU,EAAE,mBAAmB;YAC1C,UAAU,CAAC,aAAa,EAAE,mBAAmB;YAC7C,IAAA,uBAAgB,EAAC,iCAAiC,CAAC;YACnD,IAAA,uBAAgB,EAAC,4BAA4B,CAAC;YAC9C,qCAA6B,CAAC;IAEhC;;OAEG;IACH,UAAU,CAAC,yBAAyB;QAClC,UAAU,CAAC,UAAU,EAAE,yBAAyB;YAChD,UAAU,CAAC,aAAa,EAAE,yBAAyB;YACnD,IAAA,uBAAgB,EAAC,wCAAwC,CAAC;YAC1D,IAAA,uBAAgB,EAAC,mCAAmC,CAAC;YACrD,4CAAoC,CAAC;IAEvC,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AACvD,CAAC;AAxBD,8CAwBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerConfig } from './types-shim';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n"]}

@@ -1,2 +0,2 @@

export declare const VERSION = "2.8.0";
export declare const VERSION = "2.9.0";
//# sourceMappingURL=version.d.ts.map

@@ -9,3 +9,3 @@ "use strict";

// this is autogenerated file, see scripts/version-update.js
exports.VERSION = '2.8.0';
exports.VERSION = '2.9.0';
//# sourceMappingURL=version.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.8.0';\n"]}
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.9.0';\n"]}
{
"name": "@opentelemetry/sdk-trace-base",
"version": "2.8.0",
"version": "2.9.0",
"description": "OpenTelemetry Tracing",
"main": "build/src/index.js",
"module": "build/esm/index.js",
"esnext": "build/esnext/index.js",
"main": "build/src/index-shim.js",
"module": "build/esm/index-shim.js",
"esnext": "build/esnext/index-shim.js",
"browser": {

@@ -14,3 +14,3 @@ "./src/platform/index.ts": "./src/platform/browser/index.ts",

},
"types": "build/src/index.d.ts",
"types": "build/src/index-shim.d.ts",
"repository": "open-telemetry/opentelemetry-js",

@@ -24,4 +24,2 @@ "scripts": {

"test:webworker": "karma start karma.worker.js --single-run",
"test:bench": "mocha 'test/node/**/*.bench.ts' | grep 'ops/sec' | tee test/node/.benchmark-results.txt",
"test:bench:browser": "karma start karma.bench.js --single-run",
"tdd": "npm run tdd:node",

@@ -70,3 +68,4 @@ "tdd:node": "npm run test -- --watch-extensions ts --watch",

"@opentelemetry/api": ">=1.3.0 <1.10.0",
"@opentelemetry/sdk-metrics": "2.8.0",
"@opentelemetry/context-async-hooks": "2.9.0",
"@opentelemetry/sdk-metrics": "2.9.0",
"@types/benchmark": "2.1.5",

@@ -85,3 +84,3 @@ "@types/mocha": "10.0.10",

"karma-webpack": "5.0.1",
"mocha": "11.7.5",
"mocha": "11.7.6",
"nyc": "17.1.0",

@@ -97,4 +96,5 @@ "sinon": "18.0.1",

"dependencies": {
"@opentelemetry/core": "2.8.0",
"@opentelemetry/resources": "2.8.0",
"@opentelemetry/core": "2.9.0",
"@opentelemetry/resources": "2.9.0",
"@opentelemetry/sdk-trace": "2.9.0",
"@opentelemetry/semantic-conventions": "^1.29.0"

@@ -104,3 +104,3 @@ },

"sideEffects": false,
"gitHead": "13a035bc695996cf4aec885fef7b9866f48bc555"
"gitHead": "40d67b7690a61bd9af0a4e5b5b9f4a14b11fc50e"
}
import type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';
import type { TracerConfig } from './types';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
export declare enum ForceFlushState {
'resolved' = 0,
'timeout' = 1,
'error' = 2,
'unresolved' = 3
}
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
export declare class BasicTracerProvider implements TracerProvider {
private readonly _config;
private readonly _tracers;
private readonly _resource;
private readonly _activeSpanProcessor;
constructor(config?: TracerConfig);
getTracer(name: string, version?: string, options?: {
schemaUrl?: string;
}): ApiTracer;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
//# sourceMappingURL=BasicTracerProvider.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { merge } from '@opentelemetry/core';
import { defaultResource } from '@opentelemetry/resources';
import { Tracer } from './Tracer';
import { loadDefaultConfig } from './config';
import { MultiSpanProcessor } from './MultiSpanProcessor';
import { reconfigureLimits } from './utility';
import { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';
export var ForceFlushState;
(function (ForceFlushState) {
ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
ForceFlushState[ForceFlushState["error"] = 2] = "error";
ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
})(ForceFlushState || (ForceFlushState = {}));
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
export class BasicTracerProvider {
_config;
_tracers = new Map();
_resource;
_activeSpanProcessor;
constructor(config = {}) {
const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
this._resource = mergedConfig.resource ?? defaultResource();
this._config = Object.assign({}, mergedConfig, {
resource: this._resource,
});
const spanProcessors = [];
if (config.spanProcessors?.length) {
spanProcessors.push(...config.spanProcessors);
}
this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);
}
getTracer(name, version, options) {
const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;
if (!this._tracers.has(key)) {
this._tracers.set(key, new Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));
}
return this._tracers.get(key);
}
forceFlush() {
const timeout = this._config.forceFlushTimeoutMillis;
const promises = this._activeSpanProcessor['_spanProcessors'].map((spanProcessor) => {
return new Promise(resolve => {
let state;
const timeoutInterval = setTimeout(() => {
resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
state = ForceFlushState.timeout;
}, timeout);
spanProcessor
.forceFlush()
.then(() => {
clearTimeout(timeoutInterval);
if (state !== ForceFlushState.timeout) {
state = ForceFlushState.resolved;
resolve(state);
}
})
.catch(error => {
clearTimeout(timeoutInterval);
state = ForceFlushState.error;
resolve(error);
});
});
});
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(results => {
const errors = results.filter(result => result !== ForceFlushState.resolved);
if (errors.length > 0) {
reject(errors);
}
else {
resolve();
}
})
.catch(error => reject([error]));
});
}
shutdown() {
return this._activeSpanProcessor.shutdown();
}
[inspectCustom](depth, options, inspect) {
const processors = this._activeSpanProcessor['_spanProcessors'];
const payload = {
resource: { attributes: settledResourceAttributes(this._resource) },
tracers: Array.from(this._tracers.keys()),
spanProcessors: processors.map(p => p.constructor?.name ?? 'SpanProcessor'),
};
return formatInspect('BasicTracerProvider', payload, depth, options, inspect);
}
}
//# sourceMappingURL=BasicTracerProvider.js.map
{"version":3,"file":"BasicTracerProvider.js","sourceRoot":"","sources":["../../src/BasicTracerProvider.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAE3D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAE9C,OAAO,EACL,aAAa,EACb,aAAa,EACb,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AAEnB,MAAM,CAAN,IAAY,eAKX;AALD,WAAY,eAAe;IACzB,6DAAU,CAAA;IACV,2DAAS,CAAA;IACT,uDAAO,CAAA;IACP,iEAAY,CAAA;AACd,CAAC,EALW,eAAe,KAAf,eAAe,QAK1B;AAED;;GAEG;AACH,MAAM,OAAO,mBAAmB;IACb,OAAO,CAAe;IACtB,QAAQ,GAAwB,IAAI,GAAG,EAAE,CAAC;IAC1C,SAAS,CAAW;IACpB,oBAAoB,CAAqB;IAE1D,YAAY,SAAuB,EAAE;QACnC,MAAM,YAAY,GAAG,KAAK,CACxB,EAAE,EACF,iBAAiB,EAAE,EACnB,i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AC,CAAC,CAAC;QACrC,CAAC,CAAC,CAAC;IACL,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,oBAAoB,CAAC,QAAQ,EAAE,CAAC;IAC9C,CAAC;IAED,CAAC,aAAa,CAAC,CACb,KAAa,EACb,OAA0C,EAC1C,OAA8B;QAE9B,MAAM,UAAU,GAAG,IAAI,CAAC,oBAAoB,CAC1C,iBAAiB,CACC,CAAC;QACrB,MAAM,OAAO,GAAG;YACd,QAAQ,EAAE,EAAE,UAAU,EAAE,yBAAyB,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;YACnE,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;YACzC,cAAc,EAAE,UAAU,CAAC,GAAG,CAC5B,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,IAAI,IAAI,eAAe,CAC5C;SACF,CAAC;QACF,OAAO,aAAa,CAClB,qBAAqB,EACrB,OAAO,EACP,KAAK,EACL,OAAO,EACP,OAAO,CACR,CAAC;IACJ,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const processors = this._activeSpanProcessor[\n '_spanProcessors'\n ] as SpanProcessor[];\n const payload = {\n resource: { attributes: settledResourceAttributes(this._resource) },\n tracers: Array.from(this._tracers.keys()),\n spanProcessors: processors.map(\n p => p.constructor?.name ?? 'SpanProcessor'\n ),\n };\n return formatInspect(\n 'BasicTracerProvider',\n payload,\n depth,\n options,\n inspect\n );\n }\n}\n"]}
export declare const ExceptionEventName = "exception";
//# sourceMappingURL=enums.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
// Event name definitions
export const ExceptionEventName = 'exception';
//# sourceMappingURL=enums.js.map
{"version":3,"file":"enums.js","sourceRoot":"","sources":["../../src/enums.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,yBAAyB;AACzB,MAAM,CAAC,MAAM,kBAAkB,GAAG,WAAW,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n"]}
import type { Context } from '@opentelemetry/api';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
import type { BufferConfig } from '../types';
import type { ReadableSpan } from './ReadableSpan';
import type { SpanExporter } from './SpanExporter';
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
export declare abstract class BatchSpanProcessorBase<T extends BufferConfig> implements SpanProcessor {
private readonly _maxExportBatchSize;
private readonly _maxQueueSize;
private readonly _scheduledDelayMillis;
private readonly _exportTimeoutMillis;
private readonly _exporter;
private _isExporting;
private _finishedSpans;
private _timer;
private _shutdownOnce;
private _droppedSpansCount;
constructor(exporter: SpanExporter, config?: T);
forceFlush(): Promise<void>;
onStart(_span: Span, _parentContext: Context): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
private _shutdown;
/** Add a span in the buffer. */
private _addToBuffer;
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
private _flushAll;
private _flushOneBatch;
private _maybeStartTimer;
private _clearTimer;
protected abstract onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessorBase.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { context, diag, TraceFlags } from '@opentelemetry/api';
import { BindOnceFuture, ExportResultCode, getNumberFromEnv, globalErrorHandler, suppressTracing, } from '@opentelemetry/core';
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
export class BatchSpanProcessorBase {
_maxExportBatchSize;
_maxQueueSize;
_scheduledDelayMillis;
_exportTimeoutMillis;
_exporter;
_isExporting = false;
_finishedSpans = [];
_timer;
_shutdownOnce;
_droppedSpansCount = 0;
constructor(exporter, config) {
this._exporter = exporter;
this._maxExportBatchSize =
typeof config?.maxExportBatchSize === 'number'
? config.maxExportBatchSize
: (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);
this._maxQueueSize =
typeof config?.maxQueueSize === 'number'
? config.maxQueueSize
: (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);
this._scheduledDelayMillis =
typeof config?.scheduledDelayMillis === 'number'
? config.scheduledDelayMillis
: (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);
this._exportTimeoutMillis =
typeof config?.exportTimeoutMillis === 'number'
? config.exportTimeoutMillis
: (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
if (this._maxExportBatchSize > this._maxQueueSize) {
diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize');
this._maxExportBatchSize = this._maxQueueSize;
}
}
forceFlush() {
if (this._shutdownOnce.isCalled) {
return this._shutdownOnce.promise;
}
return this._flushAll();
}
// does nothing.
onStart(_span, _parentContext) { }
onEnd(span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {
return;
}
this._addToBuffer(span);
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return Promise.resolve()
.then(() => {
return this.onShutdown();
})
.then(() => {
return this._flushAll();
})
.then(() => {
return this._exporter.shutdown();
});
}
/** Add a span in the buffer. */
_addToBuffer(span) {
if (this._finishedSpans.length >= this._maxQueueSize) {
// limit reached, drop span
if (this._droppedSpansCount === 0) {
diag.debug('maxQueueSize reached, dropping spans');
}
this._droppedSpansCount++;
return;
}
if (this._droppedSpansCount > 0) {
// some spans were dropped, log once with count of spans dropped
diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
this._droppedSpansCount = 0;
}
this._finishedSpans.push(span);
this._maybeStartTimer();
}
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
_flushAll() {
return new Promise((resolve, reject) => {
const promises = [];
// calculate number of batches
const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
for (let i = 0, j = count; i < j; i++) {
promises.push(this._flushOneBatch());
}
Promise.all(promises)
.then(() => {
resolve();
})
.catch(reject);
});
}
_flushOneBatch() {
this._clearTimer();
if (this._finishedSpans.length === 0) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
// don't wait anymore for export, this way the next batch can start
reject(new Error('Timeout'));
}, this._exportTimeoutMillis);
// prevent downstream exporter calls from generating spans
context.with(suppressTracing(context.active()), () => {
// Reset the finished spans buffer here because the next invocations of the _flush method
// could pass the same finished spans to the exporter if the buffer is cleared
// outside the execution of this callback.
let spans;
if (this._finishedSpans.length <= this._maxExportBatchSize) {
spans = this._finishedSpans;
this._finishedSpans = [];
}
else {
spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
}
const doExport = () => this._exporter.export(spans, result => {
clearTimeout(timer);
if (result.code === ExportResultCode.SUCCESS) {
resolve();
}
else {
reject(result.error ??
new Error('BatchSpanProcessor: span export failed'));
}
});
let pendingResources = null;
for (let i = 0, len = spans.length; i < len; i++) {
const span = spans[i];
if (span.resource.asyncAttributesPending &&
span.resource.waitForAsyncAttributes) {
pendingResources ??= [];
pendingResources.push(span.resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources === null) {
doExport();
}
else {
Promise.all(pendingResources).then(doExport, err => {
globalErrorHandler(err);
reject(err);
});
}
});
});
}
_maybeStartTimer() {
if (this._isExporting)
return;
const flush = () => {
this._isExporting = true;
this._flushOneBatch()
.finally(() => {
this._isExporting = false;
if (this._finishedSpans.length > 0) {
this._clearTimer();
this._maybeStartTimer();
}
})
.catch(e => {
this._isExporting = false;
globalErrorHandler(e);
});
};
// we only wait if the queue doesn't have enough elements yet
if (this._finishedSpans.length >= this._maxExportBatchSize) {
return flush();
}
if (this._timer !== undefined)
return;
this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
// depending on runtime, this may be a 'number' or NodeJS.Timeout
if (typeof this._timer !== 'number') {
this._timer.unref();
}
}
_clearTimer() {
if (this._timer !== undefined) {
clearTimeout(this._timer);
this._timer = undefined;
}
}
}
//# sourceMappingURL=BatchSpanProcessorBase.js.map
{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAO7B;;;GAGG;AACH,MAAM,OAAgB,sBAAsB;I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AI,IAAI,CAAC,mBAAmB,EAAE;YAC1D,OAAO,KAAK,EAAE,CAAC;SAChB;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO;QACtC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,qBAAqB,CAAC,CAAC;QAEpE,iEAAiE;QACjE,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;SACrB;IACH,CAAC;IAEO,WAAW;QACjB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;CAGF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BufferConfig } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n"]}
import type { SpanExporter } from './SpanExporter';
import type { ReadableSpan } from './ReadableSpan';
import type { ExportResult } from '@opentelemetry/core';
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
export declare class ConsoleSpanExporter implements SpanExporter {
/**
* Export spans.
* @param spans
* @param resultCallback
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown the exporter.
*/
shutdown(): Promise<void>;
/**
* Exports any pending spans in exporter
*/
forceFlush(): Promise<void>;
/**
* converts span info into more readable format
* @param span
*/
private _exportInfo;
/**
* Showing spans in console
* @param spans
* @param done
*/
private _sendSpans;
}
//# sourceMappingURL=ConsoleSpanExporter.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
export class ConsoleSpanExporter {
/**
* Export spans.
* @param spans
* @param resultCallback
*/
export(spans, resultCallback) {
return this._sendSpans(spans, resultCallback);
}
/**
* Shutdown the exporter.
*/
shutdown() {
this._sendSpans([]);
return this.forceFlush();
}
/**
* Exports any pending spans in exporter
*/
forceFlush() {
return Promise.resolve();
}
/**
* converts span info into more readable format
* @param span
*/
_exportInfo(span) {
return {
resource: {
attributes: span.resource.attributes,
},
instrumentationScope: span.instrumentationScope,
traceId: span.spanContext().traceId,
parentSpanContext: span.parentSpanContext,
traceState: span.spanContext().traceState?.serialize(),
name: span.name,
id: span.spanContext().spanId,
kind: span.kind,
timestamp: hrTimeToMicroseconds(span.startTime),
duration: hrTimeToMicroseconds(span.duration),
attributes: span.attributes,
status: span.status,
events: span.events,
links: span.links,
};
}
/**
* Showing spans in console
* @param spans
* @param done
*/
_sendSpans(spans, done) {
for (const span of spans) {
console.dir(this._exportInfo(span), { depth: 3 });
}
if (done) {
return done({ code: ExportResultCode.SUCCESS });
}
}
}
//# sourceMappingURL=ConsoleSpanExporter.js.map
{"version":3,"file":"ConsoleSpanExporter.js","sourceRoot":"","sources":["../../../src/export/ConsoleSpanExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE7E;;;;;GAKG;AAEH,+BAA+B;AAC/B,MAAM,OAAO,mBAAmB;IAC9B;;;;OAIG;IACH,MAAM,CACJ,KAAqB,EACrB,cAA8C;QAE9C,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;IAChD,CAAC;IA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AAC,OAAO,EAAE,CAAC,CAAC;SACjD;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from './SpanExporter';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';\n\n/**\n * This is implementation of {@link SpanExporter} that prints spans to the\n * console. This class can be used for diagnostic purposes.\n *\n * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleSpanExporter implements SpanExporter {\n /**\n * Export spans.\n * @param spans\n * @param resultCallback\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n return this._sendSpans(spans, resultCallback);\n }\n\n /**\n * Shutdown the exporter.\n */\n shutdown(): Promise<void> {\n this._sendSpans([]);\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * converts span info into more readable format\n * @param span\n */\n private _exportInfo(span: ReadableSpan) {\n return {\n resource: {\n attributes: span.resource.attributes,\n },\n instrumentationScope: span.instrumentationScope,\n traceId: span.spanContext().traceId,\n parentSpanContext: span.parentSpanContext,\n traceState: span.spanContext().traceState?.serialize(),\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: hrTimeToMicroseconds(span.startTime),\n duration: hrTimeToMicroseconds(span.duration),\n attributes: span.attributes,\n status: span.status,\n events: span.events,\n links: span.links,\n };\n }\n\n /**\n * Showing spans in console\n * @param spans\n * @param done\n */\n private _sendSpans(\n spans: ReadableSpan[],\n done?: (result: ExportResult) => void\n ): void {\n for (const span of spans) {\n console.dir(this._exportInfo(span), { depth: 3 });\n }\n if (done) {\n return done({ code: ExportResultCode.SUCCESS });\n }\n }\n}\n"]}
import type { SpanExporter } from './SpanExporter';
import type { ReadableSpan } from './ReadableSpan';
import type { ExportResult } from '@opentelemetry/core';
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
export declare class InMemorySpanExporter implements SpanExporter {
private _finishedSpans;
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
protected _stopped: boolean;
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
shutdown(): Promise<void>;
/**
* Exports any pending spans in the exporter
*/
forceFlush(): Promise<void>;
reset(): void;
getFinishedSpans(): ReadableSpan[];
}
//# sourceMappingURL=InMemorySpanExporter.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { ExportResultCode } from '@opentelemetry/core';
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
export class InMemorySpanExporter {
_finishedSpans = [];
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
_stopped = false;
export(spans, resultCallback) {
if (this._stopped)
return resultCallback({
code: ExportResultCode.FAILED,
error: new Error('Exporter has been stopped'),
});
this._finishedSpans.push(...spans);
setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);
}
shutdown() {
this._stopped = true;
this._finishedSpans = [];
return this.forceFlush();
}
/**
* Exports any pending spans in the exporter
*/
forceFlush() {
return Promise.resolve();
}
reset() {
this._finishedSpans = [];
}
getFinishedSpans() {
return this._finishedSpans;
}
}
//# sourceMappingURL=InMemorySpanExporter.js.map
{"version":3,"file":"InMemorySpanExporter.js","sourceRoot":"","sources":["../../../src/export/InMemorySpanExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;;;GAIG;AACH,MAAM,OAAO,oBAAoB;IACvB,cAAc,GAAmB,EAAE,CAAC;IAC5C;;;OAGG;IACO,QAAQ,GAAG,KAAK,CAAC;IAE3B,MAAM,CACJ,KAAqB,EACrB,cAA8C;QAE9C,IAAI,IAAI,CAAC,QAAQ;YACf,OAAO,cAAc,CAAC;gBACpB,IAAI,EAAE,gBAAgB,CAAC,MAAM;gBAC7B,KAAK,EAAE,IAAI,KAAK,CAAC,2BAA2B,CAAC;aAC9C,CAAC,CAAC;QACL,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;QAEnC,UAAU,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1E,CAAC;IAED,QAAQ;QACN,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;IAC3B,CAAC;IAED,gBAAgB;QACd,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from './SpanExporter';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\n\n/**\n * This class can be used for testing purposes. It stores the exported spans\n * in a list in memory that can be retrieved using the `getFinishedSpans()`\n * method.\n */\nexport class InMemorySpanExporter implements SpanExporter {\n private _finishedSpans: ReadableSpan[] = [];\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported spans will not be stored in-memory.\n */\n protected _stopped = false;\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._stopped)\n return resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n this._finishedSpans.push(...spans);\n\n setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);\n }\n\n shutdown(): Promise<void> {\n this._stopped = true;\n this._finishedSpans = [];\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n reset(): void {\n this._finishedSpans = [];\n }\n\n getFinishedSpans(): ReadableSpan[] {\n return this._finishedSpans;\n }\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './ReadableSpan';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
/** No-op implementation of SpanProcessor */
export declare class NoopSpanProcessor implements SpanProcessor {
onStart(_span: Span, _context: Context): void;
onEnd(_span: ReadableSpan): void;
shutdown(): Promise<void>;
forceFlush(): Promise<void>;
}
//# sourceMappingURL=NoopSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/** No-op implementation of SpanProcessor */
export class NoopSpanProcessor {
onStart(_span, _context) { }
onEnd(_span) { }
shutdown() {
return Promise.resolve();
}
forceFlush() {
return Promise.resolve();
}
}
//# sourceMappingURL=NoopSpanProcessor.js.map
{"version":3,"file":"NoopSpanProcessor.js","sourceRoot":"","sources":["../../../src/export/NoopSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,4CAA4C;AAC5C,MAAM,OAAO,iBAAiB;IAC5B,OAAO,CAAC,KAAW,EAAE,QAAiB,IAAS,CAAC;IAChD,KAAK,CAAC,KAAmB,IAAS,CAAC;IACnC,QAAQ;QACN,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IACD,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\n\n/** No-op implementation of SpanProcessor */\nexport class NoopSpanProcessor implements SpanProcessor {\n onStart(_span: Span, _context: Context): void {}\n onEnd(_span: ReadableSpan): void {}\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n"]}
import type { SpanKind, SpanStatus, Attributes, HrTime, Link, SpanContext } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { TimedEvent } from '../TimedEvent';
export interface ReadableSpan {
readonly name: string;
readonly kind: SpanKind;
readonly spanContext: () => SpanContext;
readonly parentSpanContext?: SpanContext;
readonly startTime: HrTime;
readonly endTime: HrTime;
readonly status: SpanStatus;
readonly attributes: Attributes;
readonly links: Link[];
readonly events: TimedEvent[];
readonly duration: HrTime;
readonly ended: boolean;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
readonly droppedAttributesCount: number;
readonly droppedEventsCount: number;
readonly droppedLinksCount: number;
}
//# sourceMappingURL=ReadableSpan.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=ReadableSpan.js.map
{"version":3,"file":"ReadableSpan.js","sourceRoot":"","sources":["../../../src/export/ReadableSpan.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n SpanKind,\n SpanStatus,\n Attributes,\n HrTime,\n Link,\n SpanContext,\n} from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { TimedEvent } from '../TimedEvent';\n\nexport interface ReadableSpan {\n readonly name: string;\n readonly kind: SpanKind;\n readonly spanContext: () => SpanContext;\n readonly parentSpanContext?: SpanContext;\n readonly startTime: HrTime;\n readonly endTime: HrTime;\n readonly status: SpanStatus;\n readonly attributes: Attributes;\n readonly links: Link[];\n readonly events: TimedEvent[];\n readonly duration: HrTime;\n readonly ended: boolean;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n readonly droppedAttributesCount: number;\n readonly droppedEventsCount: number;\n readonly droppedLinksCount: number;\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
import type { ReadableSpan } from './ReadableSpan';
import type { SpanExporter } from './SpanExporter';
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
export declare class SimpleSpanProcessor implements SpanProcessor {
private readonly _exporter;
private _shutdownOnce;
private _pendingExports;
constructor(exporter: SpanExporter);
forceFlush(): Promise<void>;
onStart(_span: Span, _parentContext: Context): void;
onEnd(span: ReadableSpan): void;
private _doExport;
shutdown(): Promise<void>;
private _shutdown;
}
//# sourceMappingURL=SimpleSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { TraceFlags } from '@opentelemetry/api';
import { internal, ExportResultCode, globalErrorHandler, BindOnceFuture, } from '@opentelemetry/core';
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
export class SimpleSpanProcessor {
_exporter;
_shutdownOnce;
_pendingExports;
constructor(exporter) {
this._exporter = exporter;
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
this._pendingExports = new Set();
}
async forceFlush() {
await Promise.all(Array.from(this._pendingExports));
if (this._exporter.forceFlush) {
await this._exporter.forceFlush();
}
}
onStart(_span, _parentContext) { }
onEnd(span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {
return;
}
const pendingExport = this._doExport(span).catch(err => globalErrorHandler(err));
// Enqueue this export to the pending list so it can be flushed by the user.
this._pendingExports.add(pendingExport);
void pendingExport.finally(() => this._pendingExports.delete(pendingExport));
}
async _doExport(span) {
if (span.resource.asyncAttributesPending) {
// Ensure resource is fully resolved before exporting.
await span.resource.waitForAsyncAttributes?.();
}
const result = await internal._export(this._exporter, [span]);
if (result.code !== ExportResultCode.SUCCESS) {
throw (result.error ??
new Error(`SimpleSpanProcessor: span export failed (status ${result})`));
}
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return this._exporter.shutdown();
}
}
//# sourceMappingURL=SimpleSpanProcessor.js.map
{"version":3,"file":"SimpleSpanProcessor.js","sourceRoot":"","sources":["../../../src/export/SimpleSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACL,QAAQ,EACR,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACf,MAAM,qBAAqB,CAAC;AAM7B;;;;;;;GAOG;AACH,MAAM,OAAO,mBAAmB;IACb,SAAS,CAAe;IACjC,aAAa,CAAuB;IACpC,eAAe,CAAqB;IAE5C,YAAY,QAAsB;QAChC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,aAAa,GAAG,IAAI,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QAC9D,IAAI,CAAC,eAAe,GAAG,IAAI,GAAG,EAAiB,CAAC;IAClD,CAAC;IAED,KAAK,CAAC,UAAU;QAC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,MAAM,GAAG,CAAC,CACxE,CAAC;SACH;IACH,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;IACnC,CAAC;IAEO,SAAS;QACf,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IACnC,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { TraceFlags } from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n BindOnceFuture,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * An implementation of the {@link SpanProcessor} that converts the {@link Span}\n * to {@link ReadableSpan} and passes it to the configured exporter.\n *\n * Only spans that are sampled are converted.\n *\n * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.\n */\nexport class SimpleSpanProcessor implements SpanProcessor {\n private readonly _exporter: SpanExporter;\n private _shutdownOnce: BindOnceFuture<void>;\n private _pendingExports: Set<Promise<void>>;\n\n constructor(exporter: SpanExporter) {\n this._exporter = exporter;\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._pendingExports = new Set<Promise<void>>();\n }\n\n async forceFlush(): Promise<void> {\n await Promise.all(Array.from(this._pendingExports));\n if (this._exporter.forceFlush) {\n await this._exporter.forceFlush();\n }\n }\n\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n const pendingExport = this._doExport(span).catch(err =>\n globalErrorHandler(err)\n );\n // Enqueue this export to the pending list so it can be flushed by the user.\n this._pendingExports.add(pendingExport);\n void pendingExport.finally(() =>\n this._pendingExports.delete(pendingExport)\n );\n }\n\n private async _doExport(span: ReadableSpan): Promise<void> {\n if (span.resource.asyncAttributesPending) {\n // Ensure resource is fully resolved before exporting.\n await span.resource.waitForAsyncAttributes?.();\n }\n\n const result = await internal._export(this._exporter, [span]);\n if (result.code !== ExportResultCode.SUCCESS) {\n throw (\n result.error ??\n new Error(`SimpleSpanProcessor: span export failed (status ${result})`)\n );\n }\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n return this._exporter.shutdown();\n }\n}\n"]}
import type { ExportResult } from '@opentelemetry/core';
import type { ReadableSpan } from './ReadableSpan';
/**
* An interface that allows different tracing services to export recorded data
* for sampled spans in their own format.
*
* To export data this MUST be register to the Tracer SDK using a optional
* config.
*/
export interface SpanExporter {
/**
* Called to export sampled {@link ReadableSpan}s.
* @param spans the list of sampled Spans to be exported.
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/** Stops the exporter. */
shutdown(): Promise<void>;
/** Immediately export all spans */
forceFlush?(): Promise<void>;
}
//# sourceMappingURL=SpanExporter.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=SpanExporter.js.map
{"version":3,"file":"SpanExporter.js","sourceRoot":"","sources":["../../../src/export/SpanExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport type { ReadableSpan } from './ReadableSpan';\n\n/**\n * An interface that allows different tracing services to export recorded data\n * for sampled spans in their own format.\n *\n * To export data this MUST be register to the Tracer SDK using a optional\n * config.\n */\nexport interface SpanExporter {\n /**\n * Called to export sampled {@link ReadableSpan}s.\n * @param spans the list of sampled Spans to be exported.\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void;\n\n /** Stops the exporter. */\n shutdown(): Promise<void>;\n\n /** Immediately export all spans */\n forceFlush?(): Promise<void>;\n}\n"]}
/** IdGenerator provides an interface for generating Trace Id and Span Id */
export interface IdGenerator {
/** Returns a trace ID composed of 32 lowercase hex characters. */
generateTraceId(): string;
/** Returns a span ID composed of 16 lowercase hex characters. */
generateSpanId(): string;
}
//# sourceMappingURL=IdGenerator.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=IdGenerator.js.map
{"version":3,"file":"IdGenerator.js","sourceRoot":"","sources":["../../src/IdGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/** IdGenerator provides an interface for generating Trace Id and Span Id */\nexport interface IdGenerator {\n /** Returns a trace ID composed of 32 lowercase hex characters. */\n generateTraceId(): string;\n /** Returns a span ID composed of 16 lowercase hex characters. */\n generateSpanId(): string;\n}\n"]}
export { BasicTracerProvider } from './BasicTracerProvider';
export { BatchSpanProcessor, RandomIdGenerator } from './platform';
export { ConsoleSpanExporter } from './export/ConsoleSpanExporter';
export { InMemorySpanExporter } from './export/InMemorySpanExporter';
export type { ReadableSpan } from './export/ReadableSpan';
export { SimpleSpanProcessor } from './export/SimpleSpanProcessor';
export type { SpanExporter } from './export/SpanExporter';
export { NoopSpanProcessor } from './export/NoopSpanProcessor';
export { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
export { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
export { ParentBasedSampler } from './sampler/ParentBasedSampler';
export { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
export { SamplingDecision } from './Sampler';
export type { Sampler, SamplingResult } from './Sampler';
export type { Span } from './Span';
export type { SpanProcessor } from './SpanProcessor';
export type { TimedEvent } from './TimedEvent';
export type { BatchSpanProcessorBrowserConfig, BufferConfig, GeneralLimits, SDKRegistrationConfig, SpanLimits, TracerConfig, } from './types';
export type { IdGenerator } from './IdGenerator';
//# sourceMappingURL=index.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BasicTracerProvider } from './BasicTracerProvider';
export { BatchSpanProcessor, RandomIdGenerator } from './platform';
export { ConsoleSpanExporter } from './export/ConsoleSpanExporter';
export { InMemorySpanExporter } from './export/InMemorySpanExporter';
export { SimpleSpanProcessor } from './export/SimpleSpanProcessor';
export { NoopSpanProcessor } from './export/NoopSpanProcessor';
export { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
export { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
export { ParentBasedSampler } from './sampler/ParentBasedSampler';
export { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
export { SamplingDecision } from './Sampler';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BasicTracerProvider } from './BasicTracerProvider';\nexport { BatchSpanProcessor, RandomIdGenerator } from './platform';\nexport { ConsoleSpanExporter } from './export/ConsoleSpanExporter';\nexport { InMemorySpanExporter } from './export/InMemorySpanExporter';\nexport type { ReadableSpan } from './export/ReadableSpan';\nexport { SimpleSpanProcessor } from './export/SimpleSpanProcessor';\nexport type { SpanExporter } from './export/SpanExporter';\nexport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nexport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nexport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nexport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nexport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\nexport { SamplingDecision } from './Sampler';\nexport type { Sampler, SamplingResult } from './Sampler';\nexport type { Span } from './Span';\nexport type { SpanProcessor } from './SpanProcessor';\nexport type { TimedEvent } from './TimedEvent';\nexport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n GeneralLimits,\n SDKRegistrationConfig,\n SpanLimits,\n TracerConfig,\n} from './types';\nexport type { IdGenerator } from './IdGenerator';\n"]}
import type { Attributes } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
/**
* Well-known symbol used by Node.js `util.inspect` (and `console.*`) to
* render an object via a custom representation. Defined as a global Symbol
* so it works without importing from `node:util`, keeping this module safe
* for browser builds (where the symbol is simply never looked up).
*/
export declare const inspectCustom: unique symbol;
/**
* Collect a Resource's settled attributes without touching the
* `attributes` getter, which emits diag.error/debug entries when async
* attribute detectors are still pending. Promise-like (unsettled)
* entries are silently skipped so logging a Span/Tracer/Provider during
* startup doesn't recurse through the diag pipeline.
*/
export declare function settledResourceAttributes(resource: Resource): Attributes;
export type InspectFn = (value: unknown, options: unknown) => string;
export interface InspectStylizeOptions {
depth?: number | null;
stylize?: (text: string, styleType: string) => string;
}
/**
* Build a class-tagged inspect representation. Returns a stub like
* `[ClassName]` once the recursion budget is exhausted, otherwise returns
* `ClassName <inspected payload>` so nested fields keep proper coloring,
* indentation, and depth handling. In environments that don't supply an
* `inspect` callback (e.g. browsers), falls back to returning the raw
* payload object.
*/
export declare function formatInspect(className: string, payload: object, depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
//# sourceMappingURL=inspect.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Well-known symbol used by Node.js `util.inspect` (and `console.*`) to
* render an object via a custom representation. Defined as a global Symbol
* so it works without importing from `node:util`, keeping this module safe
* for browser builds (where the symbol is simply never looked up).
*/
export const inspectCustom = Symbol.for('nodejs.util.inspect.custom');
/**
* Collect a Resource's settled attributes without touching the
* `attributes` getter, which emits diag.error/debug entries when async
* attribute detectors are still pending. Promise-like (unsettled)
* entries are silently skipped so logging a Span/Tracer/Provider during
* startup doesn't recurse through the diag pipeline.
*/
export function settledResourceAttributes(resource) {
const attrs = {};
for (const [k, v] of resource.getRawAttributes()) {
if (typeof v?.then === 'function') {
continue;
}
if (v != null) {
attrs[k] ??= v;
}
}
return attrs;
}
/**
* Build a class-tagged inspect representation. Returns a stub like
* `[ClassName]` once the recursion budget is exhausted, otherwise returns
* `ClassName <inspected payload>` so nested fields keep proper coloring,
* indentation, and depth handling. In environments that don't supply an
* `inspect` callback (e.g. browsers), falls back to returning the raw
* payload object.
*/
export function formatInspect(className, payload, depth, options, inspect) {
if (typeof depth === 'number' && depth < 0) {
const tag = `[${className}]`;
return options?.stylize ? options.stylize(tag, 'special') : tag;
}
if (typeof inspect !== 'function' || !options) {
return payload;
}
const childOptions = {
...options,
depth: options.depth == null ? options.depth : options.depth - 1,
};
return `${className} ${inspect(payload, childOptions)}`;
}
//# sourceMappingURL=inspect.js.map
{"version":3,"file":"inspect.js","sourceRoot":"","sources":["../../src/inspect.ts"],"names":[],"mappings":"A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copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\n\n/**\n * Well-known symbol used by Node.js `util.inspect` (and `console.*`) to\n * render an object via a custom representation. Defined as a global Symbol\n * so it works without importing from `node:util`, keeping this module safe\n * for browser builds (where the symbol is simply never looked up).\n */\nexport const inspectCustom = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * Collect a Resource's settled attributes without touching the\n * `attributes` getter, which emits diag.error/debug entries when async\n * attribute detectors are still pending. Promise-like (unsettled)\n * entries are silently skipped so logging a Span/Tracer/Provider during\n * startup doesn't recurse through the diag pipeline.\n */\nexport function settledResourceAttributes(resource: Resource): Attributes {\n const attrs: Attributes = {};\n for (const [k, v] of resource.getRawAttributes()) {\n if (typeof (v as Partial<PromiseLike<unknown>>)?.then === 'function') {\n continue;\n }\n if (v != null) {\n attrs[k] ??= v as AttributeValue;\n }\n }\n return attrs;\n}\n\nexport type InspectFn = (value: unknown, options: unknown) => string;\n\nexport interface InspectStylizeOptions {\n depth?: number | null;\n stylize?: (text: string, styleType: string) => string;\n}\n\n/**\n * Build a class-tagged inspect representation. Returns a stub like\n * `[ClassName]` once the recursion budget is exhausted, otherwise returns\n * `ClassName <inspected payload>` so nested fields keep proper coloring,\n * indentation, and depth handling. In environments that don't supply an\n * `inspect` callback (e.g. browsers), falls back to returning the raw\n * payload object.\n */\nexport function formatInspect(\n className: string,\n payload: object,\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n): unknown {\n if (typeof depth === 'number' && depth < 0) {\n const tag = `[${className}]`;\n return options?.stylize ? options.stylize(tag, 'special') : tag;\n }\n if (typeof inspect !== 'function' || !options) {\n return payload;\n }\n const childOptions = {\n ...options,\n depth: options.depth == null ? options.depth : options.depth - 1,\n };\n return `${className} ${inspect(payload, childOptions)}`;\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './export/ReadableSpan';
import type { Span } from './Span';
import type { SpanProcessor } from './SpanProcessor';
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
export declare class MultiSpanProcessor implements SpanProcessor {
private readonly _spanProcessors;
constructor(spanProcessors: SpanProcessor[]);
forceFlush(): Promise<void>;
onStart(span: Span, context: Context): void;
onEnding(span: Span): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
}
//# sourceMappingURL=MultiSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { globalErrorHandler } from '@opentelemetry/core';
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
export class MultiSpanProcessor {
_spanProcessors;
constructor(spanProcessors) {
this._spanProcessors = spanProcessors;
}
forceFlush() {
const promises = [];
for (const spanProcessor of this._spanProcessors) {
promises.push(spanProcessor.forceFlush());
}
return new Promise(resolve => {
Promise.all(promises)
.then(() => {
resolve();
})
.catch(error => {
globalErrorHandler(error || new Error('MultiSpanProcessor: forceFlush failed'));
resolve();
});
});
}
onStart(span, context) {
for (const spanProcessor of this._spanProcessors) {
spanProcessor.onStart(span, context);
}
}
onEnding(span) {
for (const spanProcessor of this._spanProcessors) {
if (spanProcessor.onEnding) {
spanProcessor.onEnding(span);
}
}
}
onEnd(span) {
for (const spanProcessor of this._spanProcessors) {
spanProcessor.onEnd(span);
}
}
shutdown() {
const promises = [];
for (const spanProcessor of this._spanProcessors) {
promises.push(spanProcessor.shutdown());
}
return new Promise((resolve, reject) => {
Promise.all(promises).then(() => {
resolve();
}, reject);
});
}
}
//# sourceMappingURL=MultiSpanProcessor.js.map
{"version":3,"file":"MultiSpanProcessor.js","sourceRoot":"","sources":["../../src/MultiSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAKzD;;;GAGG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IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC,CAAC;SACzC;QACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;gBAC9B,OAAO,EAAE,CAAC;YACZ,CAAC,EAAE,MAAM,CAAC,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n"]}
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import type { SpanExporter } from '../../../export/SpanExporter';
import type { BatchSpanProcessorBrowserConfig } from '../../../types';
export declare class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {
private _visibilityChangeListener?;
private _pageHideListener?;
constructor(_exporter: SpanExporter, config?: BatchSpanProcessorBrowserConfig);
private onInit;
protected onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import { globalErrorHandler } from '@opentelemetry/core';
export class BatchSpanProcessor extends BatchSpanProcessorBase {
_visibilityChangeListener;
_pageHideListener;
constructor(_exporter, config) {
super(_exporter, config);
this.onInit(config);
}
onInit(config) {
if (config?.disableAutoFlushOnDocumentHide !== true &&
typeof document !== 'undefined') {
this._visibilityChangeListener = () => {
if (document.visibilityState === 'hidden') {
this.forceFlush().catch(error => {
globalErrorHandler(error);
});
}
};
this._pageHideListener = () => {
this.forceFlush().catch(error => {
globalErrorHandler(error);
});
};
document.addEventListener('visibilitychange', this._visibilityChangeListener);
// use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769
document.addEventListener('pagehide', this._pageHideListener);
}
}
onShutdown() {
if (typeof document !== 'undefined') {
if (this._visibilityChangeListener) {
document.removeEventListener('visibilitychange', this._visibilityChangeListener);
}
if (this._pageHideListener) {
document.removeEventListener('pagehide', this._pageHideListener);
}
}
}
}
//# sourceMappingURL=BatchSpanProcessor.js.map
{"version":3,"file":"BatchSpanProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/browser/export/BatchSpanProcessor.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mB,CAC1B,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;aACH;YACD,IAAI,IAAI,CAAC,iBAAiB,EAAE;gBAC1B,QAAQ,CAAC,mBAAmB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;aAClE;SACF;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { SpanExporter } from '../../../export/SpanExporter';\nimport type { BatchSpanProcessorBrowserConfig } from '../../../types';\nimport { globalErrorHandler } from '@opentelemetry/core';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {\n private _visibilityChangeListener?: () => void;\n private _pageHideListener?: () => void;\n\n constructor(\n _exporter: SpanExporter,\n config?: BatchSpanProcessorBrowserConfig\n ) {\n super(_exporter, config);\n this.onInit(config);\n }\n\n private onInit(config?: BatchSpanProcessorBrowserConfig): void {\n if (\n config?.disableAutoFlushOnDocumentHide !== true &&\n typeof document !== 'undefined'\n ) {\n this._visibilityChangeListener = () => {\n if (document.visibilityState === 'hidden') {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n }\n };\n this._pageHideListener = () => {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n };\n document.addEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n\n // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769\n document.addEventListener('pagehide', this._pageHideListener);\n }\n }\n\n protected onShutdown(): void {\n if (typeof document !== 'undefined') {\n if (this._visibilityChangeListener) {\n document.removeEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n }\n if (this._pageHideListener) {\n document.removeEventListener('pagehide', this._pageHideListener);\n }\n }\n }\n}\n"]}
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n"]}
import type { IdGenerator } from '../../IdGenerator';
export declare class RandomIdGenerator implements IdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId(): string;
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId(): string;
}
//# sourceMappingURL=RandomIdGenerator.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
const TRACE_ID_BYTES = 16;
const SPAN_ID_BYTES = 8;
const TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);
const SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);
// Byte-to-hex lookup is faster than toString(16) in browsers
const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
* Fills buffer with random bytes, ensuring at least one is non-zero
* per W3C Trace Context spec.
*/
function randomFill(buf) {
for (let i = 0; i < buf.length; i++) {
buf[i] = (Math.random() * 256) >>> 0;
}
// Ensure non-zero
for (let i = 0; i < buf.length; i++) {
if (buf[i] > 0)
return;
}
buf[buf.length - 1] = 1;
}
function toHex(buf) {
let hex = '';
for (let i = 0; i < buf.length; i++) {
hex += HEX[buf[i]];
}
return hex;
}
export class RandomIdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId() {
randomFill(TRACE_BUFFER);
return toHex(TRACE_BUFFER);
}
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId() {
randomFill(SPAN_BUFFER);
return toHex(SPAN_BUFFER);
}
}
//# sourceMappingURL=RandomIdGenerator.js.map
{"version":3,"file":"RandomIdGenerator.js","sourceRoot":"","sources":["../../../../src/platform/browser/RandomIdGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,cAAc,GAAG,EAAE,CAAC;AAC1B,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,MAAM,YAAY,GAAG,IAAI,UAAU,CAAC,cAAc,CAAC,CAAC;AACpD,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC,aAAa,CAAC,CAAC;AAElD,6DAA6D;AAC7D,MAAM,GAAG,GAAa,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACzD,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAChC,CAAC;AAEF;;;GAGG;AACH,SAAS,UAAU,CAAC,GAAe;IACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;KACtC;IACD,kBAAkB;IAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;YAAE,OAAO;KACxB;IACD,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;AAC1B,CAAC;AAED,SAAS,KAAK,CAAC,GAAe;IAC5B,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;KACpB;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,OAAO,iBAAiB;IAC5B;;;OAGG;IACH,eAAe;QACb,UAAU,CAAC,YAAY,CAAC,CAAC;QACzB,OAAO,KAAK,CAAC,YAAY,CAAC,CAAC;IAC7B,CAAC;IAED;;;OAGG;IACH,cAAc;QACZ,UAAU,CAAC,WAAW,CAAC,CAAC;QACxB,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC;IAC5B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst TRACE_ID_BYTES = 16;\nconst SPAN_ID_BYTES = 8;\n\nconst TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);\nconst SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);\n\n// Byte-to-hex lookup is faster than toString(16) in browsers\nconst HEX: string[] = Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Fills buffer with random bytes, ensuring at least one is non-zero\n * per W3C Trace Context spec.\n */\nfunction randomFill(buf: Uint8Array): void {\n for (let i = 0; i < buf.length; i++) {\n buf[i] = (Math.random() * 256) >>> 0;\n }\n // Ensure non-zero\n for (let i = 0; i < buf.length; i++) {\n if (buf[i] > 0) return;\n }\n buf[buf.length - 1] = 1;\n}\n\nfunction toHex(buf: Uint8Array): string {\n let hex = '';\n for (let i = 0; i < buf.length; i++) {\n hex += HEX[buf[i]];\n }\n return hex;\n}\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId(): string {\n randomFill(TRACE_BUFFER);\n return toHex(TRACE_BUFFER);\n }\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId(): string {\n randomFill(SPAN_BUFFER);\n return toHex(SPAN_BUFFER);\n }\n}\n"]}
export { BatchSpanProcessor, RandomIdGenerator } from './node';
//# sourceMappingURL=index.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchSpanProcessor, RandomIdGenerator } from './node';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor, RandomIdGenerator } from './node';\n"]}
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import type { BufferConfig } from '../../../types';
export declare class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {
protected onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
export class BatchSpanProcessor extends BatchSpanProcessorBase {
onShutdown() { }
}
//# sourceMappingURL=BatchSpanProcessor.js.map
{"version":3,"file":"BatchSpanProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/node/export/BatchSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAGhF,MAAM,OAAO,kBAAmB,SAAQ,sBAAoC;IAChE,UAAU,KAAU,CAAC;CAChC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n"]}
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n"]}
import type { IdGenerator } from '../../IdGenerator';
export declare class RandomIdGenerator implements IdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId: () => string;
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId: () => string;
}
//# sourceMappingURL=RandomIdGenerator.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
const SPAN_ID_BYTES = 8;
const TRACE_ID_BYTES = 16;
export class RandomIdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId = getIdGenerator(TRACE_ID_BYTES);
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId = getIdGenerator(SPAN_ID_BYTES);
}
const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
function getIdGenerator(bytes) {
return function generateId() {
for (let i = 0; i < bytes / 4; i++) {
// unsigned right shift drops decimal part of the number
// it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE
SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);
}
// If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated
for (let i = 0; i < bytes; i++) {
if (SHARED_BUFFER[i] > 0) {
break;
}
else if (i === bytes - 1) {
SHARED_BUFFER[bytes - 1] = 1;
}
}
return SHARED_BUFFER.toString('hex', 0, bytes);
};
}
//# sourceMappingURL=RandomIdGenerator.js.map
{"version":3,"file":"RandomIdGenerator.js","sourceRoot":"","sources":["../../../../src/platform/node/RandomIdGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,cAAc,GAAG,EAAE,CAAC;AAE1B,MAAM,OAAO,iBAAiB;IAC5B;;;OAGG;IACH,eAAe,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;IAEjD;;;OAGG;IACH,cAAc,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;CAChD;AAED,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;AACzD,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,SAAS,UAAU;QACxB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YAClC,wDAAwD;YACxD,gIAAgI;YAChI,aAAa,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;SACrE;QAED,sFAAsF;QACtF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YAC9B,IAAI,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE;gBACxB,MAAM;aACP;iBAAM,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE;gBAC1B,aAAa,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;aAC9B;SACF;QAED,OAAO,aAAa,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n"]}
import type { Context, Link, Attributes, SpanKind, TraceState } from '@opentelemetry/api';
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
export declare enum SamplingDecision {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
NOT_RECORD = 0,
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
RECORD = 1,
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
RECORD_AND_SAMPLED = 2
}
/**
* A sampling result contains a decision for a {@link Span} and additional
* attributes the sampler would like to added to the Span.
*/
export interface SamplingResult {
/**
* A sampling decision, refer to {@link SamplingDecision} for details.
*/
decision: SamplingDecision;
/**
* The list of attributes returned by SamplingResult MUST be immutable.
* Caller may call {@link Sampler}.shouldSample any number of times and
* can safely cache the returned value.
*/
attributes?: Readonly<Attributes>;
/**
* A {@link TraceState} that will be associated with the {@link Span} through
* the new {@link SpanContext}. Samplers SHOULD return the TraceState from
* the passed-in {@link Context} if they do not intend to change it. Leaving
* the value undefined will also leave the TraceState unchanged.
*/
traceState?: TraceState;
}
/**
* This interface represent a sampler. Sampling is a mechanism to control the
* noise and overhead introduced by OpenTelemetry by reducing the number of
* samples of traces collected and sent to the backend.
*/
export interface Sampler {
/**
* Checks whether span needs to be created and tracked.
*
* @param context Parent Context which may contain a span.
* @param traceId of the span to be created. It can be different from the
* traceId in the {@link SpanContext}. Typically in situations when the
* span to be created starts a new trace.
* @param spanName of the span to be created.
* @param spanKind of the span to be created.
* @param attributes Initial set of Attributes for the Span being constructed.
* @param links Collection of links that will be associated with the Span to
* be created. Typically useful for batch operations.
* @returns a {@link SamplingResult}.
*/
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: Attributes, links: Link[]): SamplingResult;
/** Returns the sampler name or short description with the configuration. */
toString(): string;
}
//# sourceMappingURL=Sampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
export var SamplingDecision;
(function (SamplingDecision) {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
})(SamplingDecision || (SamplingDecision = {}));
//# sourceMappingURL=Sampler.js.map
{"version":3,"file":"Sampler.js","sourceRoot":"","sources":["../../src/Sampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAUH;;;GAGG;AACH,MAAM,CAAN,IAAY,gBAgBX;AAhBD,WAAY,gBAAgB;IAC1B;;;OAGG;IACH,mEAAU,CAAA;IACV;;;OAGG;IACH,2DAAM,CAAA;IACN;;;OAGG;IACH,mFAAkB,CAAA;AACpB,CAAC,EAhBW,gBAAgB,KAAhB,gBAAgB,QAgB3B","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples no traces. */
export declare class AlwaysOffSampler implements Sampler {
shouldSample(): SamplingResult;
toString(): string;
}
//# sourceMappingURL=AlwaysOffSampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SamplingDecision } from '../Sampler';
/** Sampler that samples no traces. */
export class AlwaysOffSampler {
shouldSample() {
return {
decision: SamplingDecision.NOT_RECORD,
};
}
toString() {
return 'AlwaysOffSampler';
}
}
//# sourceMappingURL=AlwaysOffSampler.js.map
{"version":3,"file":"AlwaysOffSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysOffSampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,sCAAsC;AACtC,MAAM,OAAO,gBAAgB;IAC3B,YAAY;QACV,OAAO;YACL,QAAQ,EAAE,gBAAgB,CAAC,UAAU;SACtC,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples all traces. */
export declare class AlwaysOnSampler implements Sampler {
shouldSample(): SamplingResult;
toString(): string;
}
//# sourceMappingURL=AlwaysOnSampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SamplingDecision } from '../Sampler';
/** Sampler that samples all traces. */
export class AlwaysOnSampler {
shouldSample() {
return {
decision: SamplingDecision.RECORD_AND_SAMPLED,
};
}
toString() {
return 'AlwaysOnSampler';
}
}
//# sourceMappingURL=AlwaysOnSampler.js.map
{"version":3,"file":"AlwaysOnSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysOnSampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,uCAAuC;AACvC,MAAM,OAAO,eAAe;IAC1B,YAAY;QACV,OAAO;YACL,QAAQ,EAAE,gBAAgB,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,iBAAiB,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n"]}
import type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';
import type { Sampler, SamplingResult } from '../Sampler';
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
export declare class ParentBasedSampler implements Sampler {
private _root;
private _remoteParentSampled;
private _remoteParentNotSampled;
private _localParentSampled;
private _localParentNotSampled;
constructor(config: ParentBasedSamplerConfig);
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: Attributes, links: Link[]): SamplingResult;
toString(): string;
}
interface ParentBasedSamplerConfig {
/** Sampler called for spans with no parent */
root: Sampler;
/** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */
remoteParentSampled?: Sampler;
/** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */
remoteParentNotSampled?: Sampler;
/** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */
localParentSampled?: Sampler;
/** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */
localParentNotSampled?: Sampler;
}
export {};
//# sourceMappingURL=ParentBasedSampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';
import { globalErrorHandler } from '@opentelemetry/core';
import { AlwaysOffSampler } from './AlwaysOffSampler';
import { AlwaysOnSampler } from './AlwaysOnSampler';
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
export class ParentBasedSampler {
_root;
_remoteParentSampled;
_remoteParentNotSampled;
_localParentSampled;
_localParentNotSampled;
constructor(config) {
this._root = config.root;
if (!this._root) {
globalErrorHandler(new Error('ParentBasedSampler must have a root sampler configured'));
this._root = new AlwaysOnSampler();
}
this._remoteParentSampled =
config.remoteParentSampled ?? new AlwaysOnSampler();
this._remoteParentNotSampled =
config.remoteParentNotSampled ?? new AlwaysOffSampler();
this._localParentSampled =
config.localParentSampled ?? new AlwaysOnSampler();
this._localParentNotSampled =
config.localParentNotSampled ?? new AlwaysOffSampler();
}
shouldSample(context, traceId, spanName, spanKind, attributes, links) {
const parentContext = trace.getSpanContext(context);
if (!parentContext || !isSpanContextValid(parentContext)) {
return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.isRemote) {
if (parentContext.traceFlags & TraceFlags.SAMPLED) {
return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.traceFlags & TraceFlags.SAMPLED) {
return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
toString() {
return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
}
}
//# sourceMappingURL=ParentBasedSampler.js.map
{"version":3,"file":"ParentBas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AAC,kBAAkB,CAAC,aAAa,CAAC,EAAE;YACxD,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAC5B,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,CACN,CAAC;SACH;QAED,IAAI,aAAa,CAAC,QAAQ,EAAE;YAC1B,IAAI,aAAa,CAAC,UAAU,GAAG,UAAU,CAAC,OAAO,EAAE;gBACjD,OAAO,IAAI,CAAC,oBAAoB,CAAC,YAAY,CAC3C,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,CACN,CAAC;aACH;YACD,OAAO,IAAI,CAAC,uBAAuB,CAAC,YAAY,CAC9C,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,CACN,CAAC;SACH;QAED,IAAI,aAAa,CAAC,UAAU,GAAG,UAAU,CAAC,OAAO,EAAE;YACjD,OAAO,IAAI,CAAC,mBAAmB,CAAC,YAAY,CAC1C,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,CACN,CAAC;SACH;QAED,OAAO,IAAI,CAAC,sBAAsB,CAAC,YAAY,CAC7C,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,CACN,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,oBAAoB,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,yBAAyB,IAAI,CAAC,oBAAoB,CAAC,QAAQ,EAAE,4BAA4B,IAAI,CAAC,uBAAuB,CAAC,QAAQ,EAAE,wBAAwB,IAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE,2BAA2B,IAAI,CAAC,sBAAsB,CAAC,QAAQ,EAAE,GAAG,CAAC;IAClT,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
export declare class TraceIdRatioBasedSampler implements Sampler {
private readonly _ratio;
private _upperBound;
constructor(ratio?: number);
shouldSample(context: unknown, traceId: string): SamplingResult;
toString(): string;
private _normalize;
private _accumulate;
}
//# sourceMappingURL=TraceIdRatioBasedSampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { isValidTraceId } from '@opentelemetry/api';
import { SamplingDecision } from '../Sampler';
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
export class TraceIdRatioBasedSampler {
_ratio;
_upperBound;
constructor(ratio = 0) {
this._ratio = this._normalize(ratio);
this._upperBound = Math.floor(this._ratio * 0xffffffff);
}
shouldSample(context, traceId) {
return {
decision: isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound
? SamplingDecision.RECORD_AND_SAMPLED
: SamplingDecision.NOT_RECORD,
};
}
toString() {
return `TraceIdRatioBased{${this._ratio}}`;
}
_normalize(ratio) {
if (typeof ratio !== 'number' || isNaN(ratio))
return 0;
return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
}
_accumulate(traceId) {
let accumulation = 0;
for (let i = 0; i < 32; i += 8) {
let part = 0;
for (let j = 0; j < 8; j++) {
const c = traceId.charCodeAt(i + j);
// Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15
const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;
part = (part << 4) | v;
}
accumulation = (accumulation ^ part) >>> 0;
}
return accumulation;
}
}
//# sourceMappingURL=TraceIdRatioBasedSampler.js.map
{"version":3,"file":"TraceIdRatioBasedSampler.js","sourceRoot":"","sources":["../../../src/sampler/TraceIdRatioBasedSampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,2FAA2F;AAC3F,MAAM,OAAO,wBAAwB;IAClB,MAAM,CAAC;IAChB,WAAW,CAAS;IAE5B,YAAY,KAAK,GAAG,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACrC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC;IAC1D,CAAC;IAED,YAAY,CAAC,OAAgB,EAAE,OAAe;QAC5C,OAAO;YACL,QAAQ,EACN,cAAc,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,WAAW;gBACrE,CAAC,CAAC,gBAAgB,CAAC,kBAAkB;gBACrC,CAAC,CAAC,gBAAgB,CAAC,UAAU;SAClC,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,qBAAqB,IAAI,CAAC,MAAM,GAAG,CAAC;IAC7C,CAAC;IAEO,UAAU,CAAC,KAAa;QAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,CAAC;YAAE,OAAO,CAAC,CAAC;QACxD,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACjD,CAAC;IAEO,WAAW,CAAC,OAAe;QACjC,IAAI,YAAY,GAAG,CAAC,CAAC;QACrB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE;YAC9B,IAAI,IAAI,GAAG,CAAC,CAAC;YACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;gBAC1B,MAAM,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;gBACpC,qFAAqF;gBACrF,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;gBACrD,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;aACxB;YACD,YAAY,GAAG,CAAC,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;SAC5C;QACD,OAAO,YAAY,CAAC;IACtB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < 32; i += 8) {\n let part = 0;\n for (let j = 0; j < 8; j++) {\n const c = traceId.charCodeAt(i + j);\n // Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15\n const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;\n part = (part << 4) | v;\n }\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n"]}
/**
* Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const ATTR_OTEL_SPAN_PARENT_ORIGIN: "otel.span.parent.origin";
/**
* The result value of the sampler for this span
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const ATTR_OTEL_SPAN_SAMPLING_RESULT: "otel.span.sampling_result";
/**
* The number of created spans with `recording=true` for which the end operation has not been called yet.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const METRIC_OTEL_SDK_SPAN_LIVE: "otel.sdk.span.live";
/**
* The number of created spans.
*
* @note Implementations **MUST** record this metric for all spans, even for non-recording ones.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const METRIC_OTEL_SDK_SPAN_STARTED: "otel.sdk.span.started";
//# sourceMappingURL=semconv.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/*
* This file contains a copy of unstable semantic convention definitions
* used by this package.
* @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv
*/
/**
* Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin';
/**
* The result value of the sampler for this span
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export const ATTR_OTEL_SPAN_SAMPLING_RESULT = 'otel.span.sampling_result';
/**
* The number of created spans with `recording=true` for which the end operation has not been called yet.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live';
/**
* The number of created spans.
*
* @note Implementations **MUST** record this metric for all spans, even for non-recording ones.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started';
//# sourceMappingURL=semconv.js.map
{"version":3,"file":"semconv.js","sourceRoot":"","sources":["../../src/semconv.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,yBAAkC,CAAC;AAE/E;;;;GAIG;AACH,MAAM,CAAC,MAAM,8BAA8B,GACzC,2BAAoC,CAAC;AAEvC;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,oBAA6B,CAAC;AAEvE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,uBAAgC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n 'otel.span.sampling_result' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n"]}
import type { Context, Exception, HrTime, Link, Span as APISpan, SpanOptions as APISpanOptions, Attributes, AttributeValue, SpanContext, SpanKind, SpanStatus, TimeInput } from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { Resource } from '@opentelemetry/resources';
import type { ReadableSpan } from './export/ReadableSpan';
import type { SpanProcessor } from './SpanProcessor';
import type { TimedEvent } from './TimedEvent';
import type { SpanLimits } from './types';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
/**
* This type provides the properties of @link{ReadableSpan} at the same time
* of the Span API
*/
export type Span = APISpan & ReadableSpan;
type SpanOptions = Omit<APISpanOptions, 'root'> & {
resource: Resource;
scope: InstrumentationScope;
context: Context;
spanContext: SpanContext;
name: string;
kind: SpanKind;
parentSpanContext?: SpanContext;
spanLimits: SpanLimits;
spanProcessor: SpanProcessor;
recordEndMetrics?: () => void;
};
/**
* This class represents a span.
*/
export declare class SpanImpl implements Span {
private readonly _spanContext;
readonly kind: SpanKind;
readonly parentSpanContext?: SpanContext;
readonly attributes: Attributes;
readonly links: Link[];
readonly events: TimedEvent[];
readonly startTime: HrTime;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
private _droppedAttributesCount;
private _droppedEventsCount;
private _droppedLinksCount;
private _attributesCount;
name: string;
status: SpanStatus;
endTime: HrTime;
private _ended;
private _duration;
private readonly _spanProcessor;
private readonly _spanLimits;
private readonly _attributeValueLengthLimit;
private readonly _recordEndMetrics?;
private readonly _performanceStartTime;
private readonly _performanceOffset;
private readonly _startTimeProvided;
/**
* Constructs a new SpanImpl instance.
*/
constructor(opts: SpanOptions);
spanContext(): SpanContext;
setAttribute(key: string, value?: AttributeValue): this;
setAttributes(attributes: Attributes): this;
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name: string, attributesOrStartTime?: Attributes | TimeInput, timeStamp?: TimeInput): this;
addLink(link: Link): this;
addLinks(links: Link[]): this;
setStatus(status: SpanStatus): this;
updateName(name: string): this;
end(endTime?: TimeInput): void;
private _getTime;
isRecording(): boolean;
recordException(exception: Exception, time?: TimeInput): void;
get duration(): HrTime;
get ended(): boolean;
get droppedAttributesCount(): number;
get droppedEventsCount(): number;
get droppedLinksCount(): number;
private _isSpanEnded;
private _truncateToLimitUtil;
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
private _truncateToSize;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
export {};
//# sourceMappingURL=Span.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { diag, SpanStatusCode } from '@opentelemetry/api';
import { addHrTimes, millisToHrTime, hrTime, hrTimeDuration, isAttributeValue, isTimeInput, isTimeInputHrTime, otperformance, sanitizeAttributes, } from '@opentelemetry/core';
import { ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, } from '@opentelemetry/semantic-conventions';
import { ExceptionEventName } from './enums';
import { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';
/**
* This class represents a span.
*/
export class SpanImpl {
// Below properties are included to implement ReadableSpan for export
// purposes but are not intended to be written-to directly.
_spanContext;
kind;
parentSpanContext;
attributes = {};
links = [];
events = [];
startTime;
resource;
instrumentationScope;
_droppedAttributesCount = 0;
_droppedEventsCount = 0;
_droppedLinksCount = 0;
_attributesCount = 0;
name;
status = {
code: SpanStatusCode.UNSET,
};
endTime = [0, 0];
_ended = false;
_duration = [-1, -1];
_spanProcessor;
_spanLimits;
_attributeValueLengthLimit;
_recordEndMetrics;
_performanceStartTime;
_performanceOffset;
_startTimeProvided;
/**
* Constructs a new SpanImpl instance.
*/
constructor(opts) {
const now = Date.now();
this._spanContext = opts.spanContext;
this._performanceStartTime = otperformance.now();
this._performanceOffset =
now - (this._performanceStartTime + otperformance.timeOrigin);
this._startTimeProvided = opts.startTime != null;
this._spanLimits = opts.spanLimits;
this._attributeValueLengthLimit =
this._spanLimits.attributeValueLengthLimit ?? 0;
this._spanProcessor = opts.spanProcessor;
this.name = opts.name;
this.parentSpanContext = opts.parentSpanContext;
this.kind = opts.kind;
if (opts.links) {
for (const link of opts.links) {
this.addLink(link);
}
}
this.startTime = this._getTime(opts.startTime ?? now);
this.resource = opts.resource;
this.instrumentationScope = opts.scope;
this._recordEndMetrics = opts.recordEndMetrics;
if (opts.attributes != null) {
this.setAttributes(opts.attributes);
}
this._spanProcessor.onStart(this, opts.context);
}
spanContext() {
return this._spanContext;
}
setAttribute(key, value) {
if (value == null || this._isSpanEnded())
return this;
if (key.length === 0) {
diag.warn(`Invalid attribute key: ${key}`);
return this;
}
if (!isAttributeValue(value)) {
diag.warn(`Invalid attribute value set for key: ${key}`);
return this;
}
const { attributeCountLimit } = this._spanLimits;
const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
if (attributeCountLimit !== undefined &&
this._attributesCount >= attributeCountLimit &&
isNewKey) {
this._droppedAttributesCount++;
return this;
}
this.attributes[key] = this._truncateToSize(value);
if (isNewKey) {
this._attributesCount++;
}
return this;
}
setAttributes(attributes) {
for (const key in attributes) {
if (Object.prototype.hasOwnProperty.call(attributes, key)) {
this.setAttribute(key, attributes[key]);
}
}
return this;
}
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name, attributesOrStartTime, timeStamp) {
if (this._isSpanEnded())
return this;
const { eventCountLimit } = this._spanLimits;
if (eventCountLimit === 0) {
diag.warn('No events allowed.');
this._droppedEventsCount++;
return this;
}
if (eventCountLimit !== undefined &&
this.events.length >= eventCountLimit) {
if (this._droppedEventsCount === 0) {
diag.debug('Dropping extra events.');
}
this.events.shift();
this._droppedEventsCount++;
}
if (isTimeInput(attributesOrStartTime)) {
if (!isTimeInput(timeStamp)) {
timeStamp = attributesOrStartTime;
}
attributesOrStartTime = undefined;
}
const sanitized = sanitizeAttributes(attributesOrStartTime);
const { attributePerEventCountLimit } = this._spanLimits;
const attributes = {};
let droppedAttributesCount = 0;
let eventAttributesCount = 0;
for (const attr in sanitized) {
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
continue;
}
const attrVal = sanitized[attr];
if (attributePerEventCountLimit !== undefined &&
eventAttributesCount >= attributePerEventCountLimit) {
droppedAttributesCount++;
continue;
}
attributes[attr] = this._truncateToSize(attrVal);
eventAttributesCount++;
}
this.events.push({
name,
attributes,
time: this._getTime(timeStamp),
droppedAttributesCount,
});
return this;
}
addLink(link) {
if (this._isSpanEnded())
return this;
const { linkCountLimit } = this._spanLimits;
if (linkCountLimit === 0) {
this._droppedLinksCount++;
return this;
}
if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {
if (this._droppedLinksCount === 0) {
diag.debug('Dropping extra links.');
}
this.links.shift();
this._droppedLinksCount++;
}
const { attributePerLinkCountLimit } = this._spanLimits;
const sanitized = sanitizeAttributes(link.attributes);
const attributes = {};
let droppedAttributesCount = 0;
let linkAttributesCount = 0;
for (const attr in sanitized) {
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
continue;
}
const attrVal = sanitized[attr];
if (attributePerLinkCountLimit !== undefined &&
linkAttributesCount >= attributePerLinkCountLimit) {
droppedAttributesCount++;
continue;
}
attributes[attr] = this._truncateToSize(attrVal);
linkAttributesCount++;
}
const processedLink = { context: link.context };
if (linkAttributesCount > 0) {
processedLink.attributes = attributes;
}
if (droppedAttributesCount > 0) {
processedLink.droppedAttributesCount = droppedAttributesCount;
}
this.links.push(processedLink);
return this;
}
addLinks(links) {
for (const link of links) {
this.addLink(link);
}
return this;
}
setStatus(status) {
if (this._isSpanEnded())
return this;
if (status.code === SpanStatusCode.UNSET)
return this;
if (this.status.code === SpanStatusCode.OK)
return this;
const newStatus = { code: status.code };
// When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`,
// TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()
// as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or
// undefined to avoid an incorrect type causing issues downstream.
if (status.code === SpanStatusCode.ERROR) {
if (typeof status.message === 'string') {
newStatus.message = status.message;
}
else if (status.message != null) {
diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
}
}
this.status = newStatus;
return this;
}
updateName(name) {
if (this._isSpanEnded())
return this;
this.name = name;
return this;
}
end(endTime) {
if (this._isSpanEnded()) {
diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
return;
}
this.endTime = this._getTime(endTime);
this._duration = hrTimeDuration(this.startTime, this.endTime);
if (this._duration[0] < 0) {
diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime);
this.endTime = this.startTime.slice();
this._duration = [0, 0];
}
if (this._droppedEventsCount > 0) {
diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
}
if (this._droppedLinksCount > 0) {
diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);
}
if (this._spanProcessor.onEnding) {
this._spanProcessor.onEnding(this);
}
this._recordEndMetrics?.();
this._ended = true;
this._spanProcessor.onEnd(this);
}
_getTime(inp) {
if (typeof inp === 'number' && inp <= otperformance.now()) {
// must be a performance timestamp
// apply correction and convert to hrtime
return hrTime(inp + this._performanceOffset);
}
if (typeof inp === 'number') {
return millisToHrTime(inp);
}
if (inp instanceof Date) {
return millisToHrTime(inp.getTime());
}
if (isTimeInputHrTime(inp)) {
return inp;
}
if (this._startTimeProvided) {
// if user provided a time for the start manually
// we can't use duration to calculate event/end times
return millisToHrTime(Date.now());
}
const msDuration = otperformance.now() - this._performanceStartTime;
return addHrTimes(this.startTime, millisToHrTime(msDuration));
}
isRecording() {
return this._ended === false;
}
recordException(exception, time) {
const attributes = {};
if (typeof exception === 'string') {
attributes[ATTR_EXCEPTION_MESSAGE] = exception;
}
else if (exception) {
if (exception.code) {
attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();
}
else if (exception.name) {
attributes[ATTR_EXCEPTION_TYPE] = exception.name;
}
if (exception.message) {
attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;
}
if (exception.stack) {
attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;
}
}
// these are minimum requirements from spec
if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {
this.addEvent(ExceptionEventName, attributes, time);
}
else {
diag.warn(`Failed to record an exception ${exception}`);
}
}
get duration() {
return this._duration;
}
get ended() {
return this._ended;
}
get droppedAttributesCount() {
return this._droppedAttributesCount;
}
get droppedEventsCount() {
return this._droppedEventsCount;
}
get droppedLinksCount() {
return this._droppedLinksCount;
}
_isSpanEnded() {
if (this._ended) {
const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
}
return this._ended;
}
// Utility function to truncate given value within size
// for value type of string, will truncate to given limit
// for type of non-string, will return same value
_truncateToLimitUtil(value, limit) {
if (value.length <= limit) {
return value;
}
return value.substring(0, limit);
}
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
_truncateToSize(value) {
const limit = this._attributeValueLengthLimit;
// Check limit
if (limit <= 0) {
// Negative values are invalid, so do not truncate
diag.warn(`Attribute value limit must be positive, got ${limit}`);
return value;
}
// String
if (typeof value === 'string') {
return this._truncateToLimitUtil(value, limit);
}
// Array of strings
if (Array.isArray(value)) {
return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val);
}
// Other types, no need to apply value length limit
return value;
}
[inspectCustom](depth, options, inspect) {
const payload = {
name: this.name,
kind: this.kind,
spanContext: this._spanContext,
parentSpanContext: this.parentSpanContext,
status: this.status,
startTime: this.startTime,
endTime: this.endTime,
duration: this._duration,
ended: this._ended,
attributes: this.attributes,
events: this.events,
links: this.links,
droppedAttributesCount: this._droppedAttributesCount,
droppedEventsCount: this._droppedEventsCount,
droppedLinksCount: this._droppedLinksCount,
instrumentationScope: this.instrumentationScope,
resource: { attributes: settledResourceAttributes(this.resource) },
};
return formatInspect('SpanImpl', payload, depth, options, inspect);
}
}
//# sourceMappingURL=Span.js.map
{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAgBH,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAE1D,OAAO,EACL,UAAU,EACV,cAAc,EACd,MAAM,EACN,cAAc,EACd,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EACjB,aAAa,EACb,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAK7C,OAAO,EACL,aAAa,EACb,aAAa,EACb,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AAyBnB;;GAEG;AACH,MAAM,OAAO,QAAQ;IACnB,qEAAqE;IACrE,2DAA2D;IAC1C,YAAY,CAAc;IAClC,IAAI,CAAW;IACf,iBAAiB,CAAe;IAChC,UAAU,GAAe,EAAE,CAAC;IAC5B,KAAK,GAAW,EAAE,CAAC;IACnB,MAAM,GAAiB,EAAE,CAAC;IAC1B,SAAS,CAAS;IAClB,QAAQ,CAAW;IACnB,oBAAoB,CAAuB;IAE5C,uBAAuB,GAAG,CAAC,CAAC;IAC5B,mBAAmB,GAAW,CAAC,CAAC;IAChC,kBAAkB,GAAW,CAAC,CAAC;IAC/B,gBAAgB,GAAW,CAAC,CAAC;IAErC,IAAI,CAAS;IACb,MAAM,GAAe;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B,KAAK,EAAE,IAAI,CAAC,MAAM;YAClB,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,sBAAsB,EAAE,IAAI,CAAC,uBAAuB;YACpD,kBAAkB,EAAE,IAAI,CAAC,mBAAmB;YAC5C,iBAAiB,EAAE,IAAI,CAAC,kBAAkB;YAC1C,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,QAAQ,EAAE,EAAE,UAAU,EAAE,yBAAyB,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;SACnE,CAAC;QACF,OAAO,aAAa,CAAC,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanOptions as APISpanOptions,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n // Required here to override optional `kind` from the API's SpanOptions\n // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n private readonly _recordEndMetrics?: () => void;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit ?? 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n eventAttributesCount++;\n }\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n\n addLink(link: Link): this {\n if (this._isSpanEnded()) return this;\n\n const { linkCountLimit } = this._spanLimits;\n\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n linkAttributesCount++;\n }\n\n const processedLink: Link = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n\n this.links.push(processedLink);\n return this;\n }\n\n addLinks(links: Link[]): this {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n if (status.code === SpanStatusCode.UNSET) return this;\n if (this.status.code === SpanStatusCode.OK) return this;\n\n const newStatus: SpanStatus = { code: status.code };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n } else if (status.message != null) {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n }\n }\n\n this.status = newStatus;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(\n `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const payload = {\n name: this.name,\n kind: this.kind,\n spanContext: this._spanContext,\n parentSpanContext: this.parentSpanContext,\n status: this.status,\n startTime: this.startTime,\n endTime: this.endTime,\n duration: this._duration,\n ended: this._ended,\n attributes: this.attributes,\n events: this.events,\n links: this.links,\n droppedAttributesCount: this._droppedAttributesCount,\n droppedEventsCount: this._droppedEventsCount,\n droppedLinksCount: this._droppedLinksCount,\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this.resource) },\n };\n return formatInspect('SpanImpl', payload, depth, options, inspect);\n }\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './export/ReadableSpan';
import type { Span } from './Span';
/**
* SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks
* for when a {@link Span} is started or when a {@link Span} is ended.
*/
export interface SpanProcessor {
/**
* Forces to export all finished spans
*/
forceFlush(): Promise<void>;
/**
* Called when a {@link Span} is started, if the `span.isRecording()`
* returns true.
* @param span the Span that just started.
*/
onStart(span: Span, parentContext: Context): void;
/**
* Called when a {@link Span} is ending, if the `span.isRecording()`
* returns true.
* @param span the Span that is ending.
*
* @experimental This method is experimental and may break in minor versions of this package
*/
onEnding?(span: Span): void;
/**
* Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`
* returns true.
* @param span the Span that just ended.
*/
onEnd(span: ReadableSpan): void;
/**
* Shuts down the processor. Called when SDK is shut down. This is an
* opportunity for processor to do any cleanup required.
*/
shutdown(): Promise<void>;
}
//# sourceMappingURL=SpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=SpanProcessor.js.map
{"version":3,"file":"SpanProcessor.js","sourceRoot":"","sources":["../../src/SpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\n\n/**\n * SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks\n * for when a {@link Span} is started or when a {@link Span} is ended.\n */\nexport interface SpanProcessor {\n /**\n * Forces to export all finished spans\n */\n forceFlush(): Promise<void>;\n\n /**\n * Called when a {@link Span} is started, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just started.\n */\n onStart(span: Span, parentContext: Context): void;\n\n /**\n * Called when a {@link Span} is ending, if the `span.isRecording()`\n * returns true.\n * @param span the Span that is ending.\n *\n * @experimental This method is experimental and may break in minor versions of this package\n */\n onEnding?(span: Span): void;\n\n /**\n * Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just ended.\n */\n onEnd(span: ReadableSpan): void;\n\n /**\n * Shuts down the processor. Called when SDK is shut down. This is an\n * opportunity for processor to do any cleanup required.\n */\n shutdown(): Promise<void>;\n}\n"]}
import type { HrTime, Attributes } from '@opentelemetry/api';
/**
* Represents a timed event.
* A timed event is an event with a timestamp.
*/
export interface TimedEvent {
time: HrTime;
/** The name of the event. */
name: string;
/** The attributes of the event. */
attributes?: Attributes;
/** Count of attributes of the event that were dropped due to collection limits */
droppedAttributesCount?: number;
}
//# sourceMappingURL=TimedEvent.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=TimedEvent.js.map
{"version":3,"file":"TimedEvent.js","sourceRoot":"","sources":["../../src/TimedEvent.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime, Attributes } from '@opentelemetry/api';\n\n/**\n * Represents a timed event.\n * A timed event is an event with a timestamp.\n */\nexport interface TimedEvent {\n time: HrTime;\n /** The name of the event. */\n name: string;\n /** The attributes of the event. */\n attributes?: Attributes;\n /** Count of attributes of the event that were dropped due to collection limits */\n droppedAttributesCount?: number;\n}\n"]}
import * as api from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { GeneralLimits, SpanLimits, TracerConfig } from './types';
import type { SpanProcessor } from './SpanProcessor';
import type { Resource } from '@opentelemetry/resources';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
/**
* This class represents a basic tracer.
*/
export declare class Tracer implements api.Tracer {
private readonly _sampler;
private readonly _generalLimits;
private readonly _spanLimits;
private readonly _idGenerator;
readonly instrumentationScope: InstrumentationScope;
private readonly _resource;
private readonly _spanProcessor;
private readonly _tracerMetrics;
/**
* Constructs a new Tracer instance.
*/
constructor(instrumentationScope: InstrumentationScope, config: TracerConfig, resource: Resource, spanProcessor: SpanProcessor);
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
startSpan(name: string, options?: api.SpanOptions, context?: api.Context): api.Span;
/**
* Starts a new {@link Span} and calls the given function passing it the
* created span as first argument.
* Additionally the new span gets set in context and this context is activated
* for the duration of the function call.
*
* **Important**: The callback function is responsible for calling `span.end()`
* to finish the span. Unlike some other OpenTelemetry implementations, the span
* is NOT automatically ended when the callback returns. If `span.end()` is not
* called, the span will never be exported and will be silently lost.
*
* @param name The name of the span
* @param [options] SpanOptions used for span creation
* @param [context] Context to use to extract parent
* @param fn function called in the context of the span and receives the newly created span as an argument
* @returns return value of fn
* @example
* const something = tracer.startActiveSpan('op', span => {
* try {
* do some work
* span.setStatus({code: SpanStatusCode.OK});
* return something;
* } catch (err) {
* span.setStatus({
* code: SpanStatusCode.ERROR,
* message: err.message,
* });
* throw err;
* } finally {
* span.end();
* }
* });
* @example
* const span = tracer.startActiveSpan('op', span => {
* try {
* do some work
* return span;
* } catch (err) {
* span.setStatus({
* code: SpanStatusCode.ERROR,
* message: err.message,
* });
* throw err;
* }
* });
* do some more work
* span.end();
*/
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, fn: F): ReturnType<F>;
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, opts: api.SpanOptions, fn: F): ReturnType<F>;
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, opts: api.SpanOptions, ctx: api.Context, fn: F): ReturnType<F>;
/** Returns the active {@link GeneralLimits}. */
getGeneralLimits(): GeneralLimits;
/** Returns the active {@link SpanLimits}. */
getSpanLimits(): SpanLimits;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
//# sourceMappingURL=Tracer.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import * as api from '@opentelemetry/api';
import { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';
import { SpanImpl } from './Span';
import { mergeConfig } from './utility';
import { RandomIdGenerator } from './platform';
import { TracerMetrics } from './TracerMetrics';
import { VERSION } from './version';
import { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';
/**
* This class represents a basic tracer.
*/
export class Tracer {
_sampler;
_generalLimits;
_spanLimits;
_idGenerator;
instrumentationScope;
_resource;
_spanProcessor;
_tracerMetrics;
/**
* Constructs a new Tracer instance.
*/
constructor(instrumentationScope, config, resource, spanProcessor) {
const localConfig = mergeConfig(config);
this._sampler = localConfig.sampler;
this._generalLimits = localConfig.generalLimits;
this._spanLimits = localConfig.spanLimits;
this._idGenerator = config.idGenerator || new RandomIdGenerator();
this._resource = resource;
this._spanProcessor = spanProcessor;
this.instrumentationScope = instrumentationScope;
const meter = localConfig.meterProvider
? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)
: api.createNoopMeter();
this._tracerMetrics = new TracerMetrics(meter);
}
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
startSpan(name, options = {}, context = api.context.active()) {
// remove span from context in case a root span is requested via options
if (options.root) {
context = api.trace.deleteSpan(context);
}
const parentSpan = api.trace.getSpan(context);
if (isTracingSuppressed(context)) {
api.diag.debug('Instrumentation suppressed, returning Noop Span');
const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);
return nonRecordingSpan;
}
const parentSpanContext = parentSpan?.spanContext();
const spanId = this._idGenerator.generateSpanId();
let validParentSpanContext;
let traceId;
let traceState;
if (!parentSpanContext ||
!api.trace.isSpanContextValid(parentSpanContext)) {
// New root span.
traceId = this._idGenerator.generateTraceId();
}
else {
// New child span.
traceId = parentSpanContext.traceId;
traceState = parentSpanContext.traceState;
validParentSpanContext = parentSpanContext;
}
const spanKind = options.kind ?? api.SpanKind.INTERNAL;
const links = (options.links ?? []).map(link => {
return {
context: link.context,
attributes: sanitizeAttributes(link.attributes),
};
});
const attributes = sanitizeAttributes(options.attributes);
// make sampling decision
const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links);
const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision);
traceState = samplingResult.traceState ?? traceState;
const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED
? api.TraceFlags.SAMPLED
: api.TraceFlags.NONE;
const spanContext = { traceId, spanId, traceFlags, traceState };
if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {
api.diag.debug('Recording is off, propagating context in a non-recording span');
const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);
return nonRecordingSpan;
}
// Set initial span attributes. The attributes object may have been mutated
// by the sampler, so we sanitize the merged attributes before setting them.
const initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes));
const span = new SpanImpl({
resource: this._resource,
scope: this.instrumentationScope,
context,
spanContext,
name,
kind: spanKind,
links,
parentSpanContext: validParentSpanContext,
attributes: initAttributes,
startTime: options.startTime,
spanProcessor: this._spanProcessor,
spanLimits: this._spanLimits,
recordEndMetrics,
});
return span;
}
startActiveSpan(name, arg2, arg3, arg4) {
let opts;
let ctx;
let fn;
if (arguments.length < 2) {
return;
}
else if (arguments.length === 2) {
fn = arg2;
}
else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
}
else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
const parentContext = ctx ?? api.context.active();
const span = this.startSpan(name, opts, parentContext);
const contextWithSpanSet = api.trace.setSpan(parentContext, span);
return api.context.with(contextWithSpanSet, fn, undefined, span);
}
/** Returns the active {@link GeneralLimits}. */
getGeneralLimits() {
return this._generalLimits;
}
/** Returns the active {@link SpanLimits}. */
getSpanLimits() {
return this._spanLimits;
}
[inspectCustom](depth, options, inspect) {
const payload = {
instrumentationScope: this.instrumentationScope,
resource: { attributes: settledResourceAttributes(this._resource) },
spanLimits: this._spanLimits,
generalLimits: this._generalLimits,
};
return formatInspect('Tracer', payload, depth, options, inspect);
}
}
//# sourceMappingURL=Tracer.js.map
{"version":3,"file":"Tracer.js","sourceRoot":"","sources":["../../src/Tracer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAIxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EACL,aAAa,EACb,aAAa,EACb,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AAEnB;;GAEG;AACH,MAAM,OAAO,MAAM;IACA,QAAQ,CAAU;IAClB,cAAc,CAAgB;IAC9B,WAAW,CAAa;IACxB,YAAY,CAAc;IAClC,oBAAoB,CAAuB;IAEnC,SAAS,CAAW;IACpB,cAAc,CAAgB;IAC9B,cAAc,CAAgB;IAE/C;;OAEG;IACH,YACE,oBAA0C,EAC1C,MAAoB,EACpB,QAAkB,EAClB,aAA4B;QAE5B,MAAM,WAAW,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC;QACxC,IAAI,CAAC,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC;QACpC,IAAI,CAAC,cAAc,GAAG,WAAW,CAAC,aAAa,CAAC;QAChD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC,UAAU,CAAC;QAC1C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,WAAW,IAAI,IAAI,iBAAiB,EAAE,CAA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C;YAC3C,GAAG,GAAG,IAA+B,CAAC;YACtC,EAAE,GAAG,IAAS,CAAC;SAChB;QAED,MAAM,aAAa,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;QAClD,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC;QACvD,MAAM,kBAAkB,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QAElE,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACnE,CAAC;IAED,gDAAgD;IAChD,gBAAgB;QACd,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;IAED,6CAA6C;IAC7C,aAAa;QACX,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;IAED,CAAC,aAAa,CAAC,CACb,KAAa,EACb,OAA0C,EAC1C,OAA8B;QAE9B,MAAM,OAAO,GAAG;YACd,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,QAAQ,EAAE,EAAE,UAAU,EAAE,yBAAyB,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;YACnE,UAAU,EAAE,IAAI,CAAC,WAAW;YAC5B,aAAa,EAAE,IAAI,CAAC,cAAc;SACnC,CAAC;QACF,OAAO,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACnE,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n private readonly _tracerMetrics: TracerMetrics;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n\n const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\n this._tracerMetrics = new TracerMetrics(meter);\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n const recordEndMetrics = this._tracerMetrics.startSpan(\n parentSpanContext,\n samplingResult.decision\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n recordEndMetrics,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * **Important**: The callback function is responsible for calling `span.end()`\n * to finish the span. Unlike some other OpenTelemetry implementations, the span\n * is NOT automatically ended when the callback returns. If `span.end()` is not\n * called, the span will never be exported and will be silently lost.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const payload = {\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this._resource) },\n spanLimits: this._spanLimits,\n generalLimits: this._generalLimits,\n };\n return formatInspect('Tracer', payload, depth, options, inspect);\n }\n}\n"]}
import type { Meter, SpanContext } from '@opentelemetry/api';
import { SamplingDecision } from './Sampler';
/**
* Generates `otel.sdk.span.*` metrics.
* https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
*/
export declare class TracerMetrics {
private readonly startedSpans;
private readonly liveSpans;
constructor(meter: Meter);
startSpan(parentSpanCtx: SpanContext | undefined, samplingDecision: SamplingDecision): () => void;
}
//# sourceMappingURL=TracerMetrics.d.ts.map
import { SamplingDecision } from './Sampler';
import { ATTR_OTEL_SPAN_PARENT_ORIGIN, ATTR_OTEL_SPAN_SAMPLING_RESULT, METRIC_OTEL_SDK_SPAN_LIVE, METRIC_OTEL_SDK_SPAN_STARTED, } from './semconv';
/**
* Generates `otel.sdk.span.*` metrics.
* https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
*/
export class TracerMetrics {
startedSpans;
liveSpans;
constructor(meter) {
this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {
unit: '{span}',
description: 'The number of created spans.',
});
this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {
unit: '{span}',
description: 'The number of currently live spans.',
});
}
startSpan(parentSpanCtx, samplingDecision) {
const samplingDecisionStr = samplingDecisionToString(samplingDecision);
this.startedSpans.add(1, {
[ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),
[ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,
});
if (samplingDecision === SamplingDecision.NOT_RECORD) {
return () => { };
}
const liveSpanAttributes = {
[ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,
};
this.liveSpans.add(1, liveSpanAttributes);
return () => {
this.liveSpans.add(-1, liveSpanAttributes);
};
}
}
function parentOrigin(parentSpanContext) {
if (!parentSpanContext) {
return 'none';
}
if (parentSpanContext.isRemote) {
return 'remote';
}
return 'local';
}
function samplingDecisionToString(decision) {
switch (decision) {
case SamplingDecision.RECORD_AND_SAMPLED:
return 'RECORD_AND_SAMPLE';
case SamplingDecision.RECORD:
return 'RECORD_ONLY';
case SamplingDecision.NOT_RECORD:
return 'DROP';
}
}
//# sourceMappingURL=TracerMetrics.js.map
{"version":3,"file":"TracerMetrics.js","sourceRoot":"","sources":["../../src/TracerMetrics.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EACL,4BAA4B,EAC5B,8BAA8B,EAC9B,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,WAAW,CAAC;AAEnB;;;GAGG;AACH,MAAM,OAAO,aAAa;IACP,YAAY,CAAU;IACtB,SAAS,CAAgB;IAE1C,YAAY,KAAY;QACtB,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC,aAAa,CAAC,4BAA4B,EAAE;YACpE,IAAI,EAAE,QAAQ;YACd,WAAW,EAAE,8BAA8B;SAC5C,CAAC,CAAC;QAEH,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,yBAAyB,EAAE;YACpE,IAAI,EAAE,QAAQ;YACd,WAAW,EAAE,qCAAqC;SACnD,CAAC,CAAC;IACL,CAAC;IAED,SAAS,CACP,aAAsC,EACtC,gBAAkC;QAElC,MAAM,mBAAmB,GAAG,wBAAwB,CAAC,gBAAgB,CAAC,CAAC;QACvE,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE;YACvB,CAAC,4BAA4B,CAAC,EAAE,YAAY,CAAC,aAAa,CAAC;YAC3D,CAAC,8BAA8B,CAAC,EAAE,mBAAmB;SACtD,CAAC,CAAC;QAEH,IAAI,gBAAgB,KAAK,gBAAgB,CAAC,UAAU,EAAE;YACpD,OAAO,GAAG,EAAE,GAAE,CAAC,CAAC;SACjB;QAED,MAAM,kBAAkB,GAAG;YACzB,CAAC,8BAA8B,CAAC,EAAE,mBAAmB;SACtD,CAAC;QACF,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE,kBAAkB,CAAC,CAAC;QAC1C,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,kBAAkB,CAAC,CAAC;QAC7C,CAAC,CAAC;IACJ,CAAC;CACF;AAED,SAAS,YAAY,CAAC,iBAA0C;IAC9D,IAAI,CAAC,iBAAiB,EAAE;QACtB,OAAO,MAAM,CAAC;KACf;IACD,IAAI,iBAAiB,CAAC,QAAQ,EAAE;QAC9B,OAAO,QAAQ,CAAC;KACjB;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,wBAAwB,CAAC,QAA0B;IAC1D,QAAQ,QAAQ,EAAE;QAChB,KAAK,gBAAgB,CAAC,kBAAkB;YACtC,OAAO,mBAAmB,CAAC;QAC7B,KAAK,gBAAgB,CAAC,MAAM;YAC1B,OAAO,aAAa,CAAC;QACvB,KAAK,gBAAgB,CAAC,UAAU;YAC9B,OAAO,MAAM,CAAC;KACjB;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Counter,\n Meter,\n SpanContext,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n ATTR_OTEL_SPAN_PARENT_ORIGIN,\n ATTR_OTEL_SPAN_SAMPLING_RESULT,\n METRIC_OTEL_SDK_SPAN_LIVE,\n METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n private readonly startedSpans: Counter;\n private readonly liveSpans: UpDownCounter;\n\n constructor(meter: Meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n\n startSpan(\n parentSpanCtx: SpanContext | undefined,\n samplingDecision: SamplingDecision\n ): () => void {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => {};\n }\n\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n"]}
import type { ContextManager, MeterProvider, TextMapPropagator } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
import type { IdGenerator } from './IdGenerator';
import type { Sampler } from './Sampler';
import type { SpanProcessor } from './SpanProcessor';
/**
* TracerConfig provides an interface for configuring a Basic Tracer.
*/
export interface TracerConfig {
/**
* Sampler determines if a span should be recorded or should be a NoopSpan.
*/
sampler?: Sampler;
/** General Limits */
generalLimits?: GeneralLimits;
/** Span Limits */
spanLimits?: SpanLimits;
/** Resource associated with trace telemetry */
resource?: Resource;
/**
* Generator of trace and span IDs
* The default idGenerator generates random ids
*/
idGenerator?: IdGenerator;
/**
* How long the forceFlush can run before it is cancelled.
* The default value is 30000ms
*/
forceFlushTimeoutMillis?: number;
/**
* List of SpanProcessor for the tracer
*/
spanProcessors?: SpanProcessor[];
/**
* A meter provider to record trace SDK metrics to.
* @experimental This option is experimental and is subject to breaking changes in minor releases.
*/
meterProvider?: MeterProvider;
}
/**
* Configuration options for registering the API with the SDK.
* Undefined values may be substituted for defaults, and null
* values will not be registered.
*/
export interface SDKRegistrationConfig {
/** Propagator to register as the global propagator */
propagator?: TextMapPropagator | null;
/** Context manager to register as the global context manager */
contextManager?: ContextManager | null;
}
/** Global configuration limits of trace service */
export interface GeneralLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per trace */
attributeCountLimit?: number;
}
/** Global configuration of trace service */
export interface SpanLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per span */
attributeCountLimit?: number;
/** linkCountLimit is number of links per span */
linkCountLimit?: number;
/** eventCountLimit is number of message events per span */
eventCountLimit?: number;
/** attributePerEventCountLimit is the maximum number of attributes allowed per span event */
attributePerEventCountLimit?: number;
/** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */
attributePerLinkCountLimit?: number;
}
/** Interface configuration for a buffer. */
export interface BufferConfig {
/** The maximum batch size of every export. It must be smaller or equal to
* maxQueueSize. The default value is 512. */
maxExportBatchSize?: number;
/** The delay interval in milliseconds between two consecutive exports.
* The default value is 5000ms. */
scheduledDelayMillis?: number;
/** How long the export can run before it is cancelled.
* The default value is 30000ms */
exportTimeoutMillis?: number;
/** The maximum queue size. After the size is reached spans are dropped.
* The default value is 2048. */
maxQueueSize?: number;
}
/** Interface configuration for BatchSpanProcessor on browser */
export interface BatchSpanProcessorBrowserConfig extends BufferConfig {
/** Disable flush when a user navigates to a new page, closes the tab or the browser, or,
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}
//# sourceMappingURL=types.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=types.js.map
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n ContextManager,\n MeterProvider,\n TextMapPropagator,\n} from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { IdGenerator } from './IdGenerator';\nimport type { Sampler } from './Sampler';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * TracerConfig provides an interface for configuring a Basic Tracer.\n */\nexport interface TracerConfig {\n /**\n * Sampler determines if a span should be recorded or should be a NoopSpan.\n */\n sampler?: Sampler;\n\n /** General Limits */\n generalLimits?: GeneralLimits;\n\n /** Span Limits */\n spanLimits?: SpanLimits;\n\n /** Resource associated with trace telemetry */\n resource?: Resource;\n\n /**\n * Generator of trace and span IDs\n * The default idGenerator generates random ids\n */\n idGenerator?: IdGenerator;\n\n /**\n * How long the forceFlush can run before it is cancelled.\n * The default value is 30000ms\n */\n forceFlushTimeoutMillis?: number;\n\n /**\n * List of SpanProcessor for the tracer\n */\n spanProcessors?: SpanProcessor[];\n\n /**\n * A meter provider to record trace SDK metrics to.\n * @experimental This option is experimental and is subject to breaking changes in minor releases.\n */\n meterProvider?: MeterProvider;\n}\n\n/**\n * Configuration options for registering the API with the SDK.\n * Undefined values may be substituted for defaults, and null\n * values will not be registered.\n */\nexport interface SDKRegistrationConfig {\n /** Propagator to register as the global propagator */\n propagator?: TextMapPropagator | null;\n\n /** Context manager to register as the global context manager */\n contextManager?: ContextManager | null;\n}\n\n/** Global configuration limits of trace service */\nexport interface GeneralLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per trace */\n attributeCountLimit?: number;\n}\n\n/** Global configuration of trace service */\nexport interface SpanLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per span */\n attributeCountLimit?: number;\n /** linkCountLimit is number of links per span */\n linkCountLimit?: number;\n /** eventCountLimit is number of message events per span */\n eventCountLimit?: number;\n /** attributePerEventCountLimit is the maximum number of attributes allowed per span event */\n attributePerEventCountLimit?: number;\n /** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */\n attributePerLinkCountLimit?: number;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached spans are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\n/** Interface configuration for BatchSpanProcessor on browser */\nexport interface BatchSpanProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n"]}
import type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';
import type { TracerConfig } from './types';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
export declare enum ForceFlushState {
'resolved' = 0,
'timeout' = 1,
'error' = 2,
'unresolved' = 3
}
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
export declare class BasicTracerProvider implements TracerProvider {
private readonly _config;
private readonly _tracers;
private readonly _resource;
private readonly _activeSpanProcessor;
constructor(config?: TracerConfig);
getTracer(name: string, version?: string, options?: {
schemaUrl?: string;
}): ApiTracer;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
//# sourceMappingURL=BasicTracerProvider.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { merge } from '@opentelemetry/core';
import { defaultResource } from '@opentelemetry/resources';
import { Tracer } from './Tracer';
import { loadDefaultConfig } from './config';
import { MultiSpanProcessor } from './MultiSpanProcessor';
import { reconfigureLimits } from './utility';
import { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';
export var ForceFlushState;
(function (ForceFlushState) {
ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
ForceFlushState[ForceFlushState["error"] = 2] = "error";
ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
})(ForceFlushState || (ForceFlushState = {}));
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
export class BasicTracerProvider {
_config;
_tracers = new Map();
_resource;
_activeSpanProcessor;
constructor(config = {}) {
const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
this._resource = mergedConfig.resource ?? defaultResource();
this._config = Object.assign({}, mergedConfig, {
resource: this._resource,
});
const spanProcessors = [];
if (config.spanProcessors?.length) {
spanProcessors.push(...config.spanProcessors);
}
this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);
}
getTracer(name, version, options) {
const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;
if (!this._tracers.has(key)) {
this._tracers.set(key, new Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));
}
return this._tracers.get(key);
}
forceFlush() {
const timeout = this._config.forceFlushTimeoutMillis;
const promises = this._activeSpanProcessor['_spanProcessors'].map((spanProcessor) => {
return new Promise(resolve => {
let state;
const timeoutInterval = setTimeout(() => {
resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
state = ForceFlushState.timeout;
}, timeout);
spanProcessor
.forceFlush()
.then(() => {
clearTimeout(timeoutInterval);
if (state !== ForceFlushState.timeout) {
state = ForceFlushState.resolved;
resolve(state);
}
})
.catch(error => {
clearTimeout(timeoutInterval);
state = ForceFlushState.error;
resolve(error);
});
});
});
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(results => {
const errors = results.filter(result => result !== ForceFlushState.resolved);
if (errors.length > 0) {
reject(errors);
}
else {
resolve();
}
})
.catch(error => reject([error]));
});
}
shutdown() {
return this._activeSpanProcessor.shutdown();
}
[inspectCustom](depth, options, inspect) {
const processors = this._activeSpanProcessor['_spanProcessors'];
const payload = {
resource: { attributes: settledResourceAttributes(this._resource) },
tracers: Array.from(this._tracers.keys()),
spanProcessors: processors.map(p => p.constructor?.name ?? 'SpanProcessor'),
};
return formatInspect('BasicTracerProvider', payload, depth, options, inspect);
}
}
//# sourceMappingURL=BasicTracerProvider.js.map
{"version":3,"file":"BasicTracerProvider.js","sourceRoot":"","sources":["../../src/BasicTracerProvider.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAE3D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,s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*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const processors = this._activeSpanProcessor[\n '_spanProcessors'\n ] as SpanProcessor[];\n const payload = {\n resource: { attributes: settledResourceAttributes(this._resource) },\n tracers: Array.from(this._tracers.keys()),\n spanProcessors: processors.map(\n p => p.constructor?.name ?? 'SpanProcessor'\n ),\n };\n return formatInspect(\n 'BasicTracerProvider',\n payload,\n depth,\n options,\n inspect\n );\n }\n}\n"]}
export declare const ExceptionEventName = "exception";
//# sourceMappingURL=enums.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
// Event name definitions
export const ExceptionEventName = 'exception';
//# sourceMappingURL=enums.js.map
{"version":3,"file":"enums.js","sourceRoot":"","sources":["../../src/enums.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,yBAAyB;AACzB,MAAM,CAAC,MAAM,kBAAkB,GAAG,WAAW,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n"]}
import type { Context } from '@opentelemetry/api';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
import type { BufferConfig } from '../types';
import type { ReadableSpan } from './ReadableSpan';
import type { SpanExporter } from './SpanExporter';
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
export declare abstract class BatchSpanProcessorBase<T extends BufferConfig> implements SpanProcessor {
private readonly _maxExportBatchSize;
private readonly _maxQueueSize;
private readonly _scheduledDelayMillis;
private readonly _exportTimeoutMillis;
private readonly _exporter;
private _isExporting;
private _finishedSpans;
private _timer;
private _shutdownOnce;
private _droppedSpansCount;
constructor(exporter: SpanExporter, config?: T);
forceFlush(): Promise<void>;
onStart(_span: Span, _parentContext: Context): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
private _shutdown;
/** Add a span in the buffer. */
private _addToBuffer;
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
private _flushAll;
private _flushOneBatch;
private _maybeStartTimer;
private _clearTimer;
protected abstract onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessorBase.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { context, diag, TraceFlags } from '@opentelemetry/api';
import { BindOnceFuture, ExportResultCode, getNumberFromEnv, globalErrorHandler, suppressTracing, } from '@opentelemetry/core';
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
export class BatchSpanProcessorBase {
_maxExportBatchSize;
_maxQueueSize;
_scheduledDelayMillis;
_exportTimeoutMillis;
_exporter;
_isExporting = false;
_finishedSpans = [];
_timer;
_shutdownOnce;
_droppedSpansCount = 0;
constructor(exporter, config) {
this._exporter = exporter;
this._maxExportBatchSize =
typeof config?.maxExportBatchSize === 'number'
? config.maxExportBatchSize
: (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);
this._maxQueueSize =
typeof config?.maxQueueSize === 'number'
? config.maxQueueSize
: (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);
this._scheduledDelayMillis =
typeof config?.scheduledDelayMillis === 'number'
? config.scheduledDelayMillis
: (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);
this._exportTimeoutMillis =
typeof config?.exportTimeoutMillis === 'number'
? config.exportTimeoutMillis
: (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
if (this._maxExportBatchSize > this._maxQueueSize) {
diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize');
this._maxExportBatchSize = this._maxQueueSize;
}
}
forceFlush() {
if (this._shutdownOnce.isCalled) {
return this._shutdownOnce.promise;
}
return this._flushAll();
}
// does nothing.
onStart(_span, _parentContext) { }
onEnd(span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {
return;
}
this._addToBuffer(span);
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return Promise.resolve()
.then(() => {
return this.onShutdown();
})
.then(() => {
return this._flushAll();
})
.then(() => {
return this._exporter.shutdown();
});
}
/** Add a span in the buffer. */
_addToBuffer(span) {
if (this._finishedSpans.length >= this._maxQueueSize) {
// limit reached, drop span
if (this._droppedSpansCount === 0) {
diag.debug('maxQueueSize reached, dropping spans');
}
this._droppedSpansCount++;
return;
}
if (this._droppedSpansCount > 0) {
// some spans were dropped, log once with count of spans dropped
diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
this._droppedSpansCount = 0;
}
this._finishedSpans.push(span);
this._maybeStartTimer();
}
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
_flushAll() {
return new Promise((resolve, reject) => {
const promises = [];
// calculate number of batches
const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
for (let i = 0, j = count; i < j; i++) {
promises.push(this._flushOneBatch());
}
Promise.all(promises)
.then(() => {
resolve();
})
.catch(reject);
});
}
_flushOneBatch() {
this._clearTimer();
if (this._finishedSpans.length === 0) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
// don't wait anymore for export, this way the next batch can start
reject(new Error('Timeout'));
}, this._exportTimeoutMillis);
// prevent downstream exporter calls from generating spans
context.with(suppressTracing(context.active()), () => {
// Reset the finished spans buffer here because the next invocations of the _flush method
// could pass the same finished spans to the exporter if the buffer is cleared
// outside the execution of this callback.
let spans;
if (this._finishedSpans.length <= this._maxExportBatchSize) {
spans = this._finishedSpans;
this._finishedSpans = [];
}
else {
spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
}
const doExport = () => this._exporter.export(spans, result => {
clearTimeout(timer);
if (result.code === ExportResultCode.SUCCESS) {
resolve();
}
else {
reject(result.error ??
new Error('BatchSpanProcessor: span export failed'));
}
});
let pendingResources = null;
for (let i = 0, len = spans.length; i < len; i++) {
const span = spans[i];
if (span.resource.asyncAttributesPending &&
span.resource.waitForAsyncAttributes) {
pendingResources ??= [];
pendingResources.push(span.resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources === null) {
doExport();
}
else {
Promise.all(pendingResources).then(doExport, err => {
globalErrorHandler(err);
reject(err);
});
}
});
});
}
_maybeStartTimer() {
if (this._isExporting)
return;
const flush = () => {
this._isExporting = true;
this._flushOneBatch()
.finally(() => {
this._isExporting = false;
if (this._finishedSpans.length > 0) {
this._clearTimer();
this._maybeStartTimer();
}
})
.catch(e => {
this._isExporting = false;
globalErrorHandler(e);
});
};
// we only wait if the queue doesn't have enough elements yet
if (this._finishedSpans.length >= this._maxExportBatchSize) {
return flush();
}
if (this._timer !== undefined)
return;
this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
// depending on runtime, this may be a 'number' or NodeJS.Timeout
if (typeof this._timer !== 'number') {
this._timer.unref();
}
}
_clearTimer() {
if (this._timer !== undefined) {
clearTimeout(this._timer);
this._timer = undefined;
}
}
}
//# sourceMappingURL=BatchSpanProcessorBase.js.map
{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAO7B;;;GAGG;AACH,MAAM,OAAgB,sBAAsB;IAGzB,mBAAmB,CAAS;IAC5B,aAAa,CAAS;IACtB,qBAAqB,CAAS;IAC9B,oBAAoB,CAAS;IAC7B,SAAS,CAAe;IAEjC,YAAY,GAAG,KAAK,CAAC;IACrB,cAAc,GAAmB,EAAE,CAAC;IACpC,MAAM,CAAsC;IAC5C,aAAa,CAAuB;IACpC,kBAAkB,GAAW,CAAC,CAAC;IAEvC,YAAY,QAAsB,EAAE,MAAU;QAC5C,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,mBAAmB;YACtB,OAAO,MAAM,EAAE,kBAAkB,KAAK,QAAQ;gBAC5C,CAAC,CAAC,MAAM,CAAC,kBAAkB;gBAC3B,CAAC,CAAC,CAAC,gBAAgB,CAAC,gCAAgC,CAAC,IAAI,GAAG,CAAC,CAAC;QAClE,IAAI,CAAC,aAAa;YAChB,OAAO,MAAM,EAAE,YAAY,KAAK,QAAQ;gBACtC,CAAC,CAAC,MAAM,CAAC,YAAY;gBACrB,CAAC,CAAC,CAAC,gBAAgB,CAAC,yBAAyB,CAAC,IAAI,IAAI,CAAC,CAAC;QAC5D,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EAAE;YACjB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;YACzB,IAAI,CAAC,cAAc,EAAE;iBAClB,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;gBAC1B,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE;oBAClC,IAAI,CAAC,WAAW,EAAE,CAAC;oBACnB,IAAI,CAAC,gBAAgB,EAAE,CAAC;iBACzB;YACH,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,CAAC,EAAE;gBACT,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;gBAC1B,kBAAkB,CAAC,CAAC,CAAC,CAAC;YACxB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QACF,6DAA6D;QAC7D,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,IAAI,IAAI,CAAC,mBAAmB,EAAE;YAC1D,OAAO,KAAK,EAAE,CAAC;SAChB;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO;QACtC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,qBAAqB,CAAC,CAAC;QAEpE,iEAAiE;QACjE,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;SACrB;IACH,CAAC;IAEO,WAAW;QACjB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;CAGF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BufferConfig } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n"]}
import type { SpanExporter } from './SpanExporter';
import type { ReadableSpan } from './ReadableSpan';
import type { ExportResult } from '@opentelemetry/core';
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
export declare class ConsoleSpanExporter implements SpanExporter {
/**
* Export spans.
* @param spans
* @param resultCallback
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown the exporter.
*/
shutdown(): Promise<void>;
/**
* Exports any pending spans in exporter
*/
forceFlush(): Promise<void>;
/**
* converts span info into more readable format
* @param span
*/
private _exportInfo;
/**
* Showing spans in console
* @param spans
* @param done
*/
private _sendSpans;
}
//# sourceMappingURL=ConsoleSpanExporter.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
export class ConsoleSpanExporter {
/**
* Export spans.
* @param spans
* @param resultCallback
*/
export(spans, resultCallback) {
return this._sendSpans(spans, resultCallback);
}
/**
* Shutdown the exporter.
*/
shutdown() {
this._sendSpans([]);
return this.forceFlush();
}
/**
* Exports any pending spans in exporter
*/
forceFlush() {
return Promise.resolve();
}
/**
* converts span info into more readable format
* @param span
*/
_exportInfo(span) {
return {
resource: {
attributes: span.resource.attributes,
},
instrumentationScope: span.instrumentationScope,
traceId: span.spanContext().traceId,
parentSpanContext: span.parentSpanContext,
traceState: span.spanContext().traceState?.serialize(),
name: span.name,
id: span.spanContext().spanId,
kind: span.kind,
timestamp: hrTimeToMicroseconds(span.startTime),
duration: hrTimeToMicroseconds(span.duration),
attributes: span.attributes,
status: span.status,
events: span.events,
links: span.links,
};
}
/**
* Showing spans in console
* @param spans
* @param done
*/
_sendSpans(spans, done) {
for (const span of spans) {
console.dir(this._exportInfo(span), { depth: 3 });
}
if (done) {
return done({ code: ExportResultCode.SUCCESS });
}
}
}
//# sourceMappingURL=ConsoleSpanExporter.js.map
{"version":3,"file":"ConsoleSpanExporter.js","sourceRoot":"","sources":["../../../src/export/ConsoleSpanExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE7E;;;;;GAKG;AAEH,+BAA+B;AAC/B,MAAM,OAAO,mBAAmB;IAC9B;;;;OAIG;IACH,MAAM,CACJ,KAAqB,EACrB,cAA8C;QAE9C,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED;;;OAGG;IACK,WAAW,CAAC,IAAkB;QACpC,OAAO;YACL,QAAQ,EAAE;gBACR,UAAU,EAAE,IAAI,CAAC,QAAQ,CAAC,UAAU;aACrC;YACD,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO;YACnC,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,UAAU,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,UAAU,EAAE,SAAS,EAAE;YACtD,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,EAAE,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,MAAM;YAC7B,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,oBAAoB,CAAC,IAAI,CAAC,SAAS,CAAC;YAC/C,QAAQ,EAAE,oBAAoB,CAAC,IAAI,CAAC,QAAQ,CAAC;YAC7C,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACK,UAAU,CAChB,KAAqB,EACrB,IAAqC;QAErC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;YACxB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;SACnD;QACD,IAAI,IAAI,EAAE;YACR,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;SACjD;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from './SpanExporter';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';\n\n/**\n * This is implementation of {@link SpanExporter} that prints spans to the\n * console. This class can be used for diagnostic purposes.\n *\n * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleSpanExporter implements SpanExporter {\n /**\n * Export spans.\n * @param spans\n * @param resultCallback\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n return this._sendSpans(spans, resultCallback);\n }\n\n /**\n * Shutdown the exporter.\n */\n shutdown(): Promise<void> {\n this._sendSpans([]);\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * converts span info into more readable format\n * @param span\n */\n private _exportInfo(span: ReadableSpan) {\n return {\n resource: {\n attributes: span.resource.attributes,\n },\n instrumentationScope: span.instrumentationScope,\n traceId: span.spanContext().traceId,\n parentSpanContext: span.parentSpanContext,\n traceState: span.spanContext().traceState?.serialize(),\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: hrTimeToMicroseconds(span.startTime),\n duration: hrTimeToMicroseconds(span.duration),\n attributes: span.attributes,\n status: span.status,\n events: span.events,\n links: span.links,\n };\n }\n\n /**\n * Showing spans in console\n * @param spans\n * @param done\n */\n private _sendSpans(\n spans: ReadableSpan[],\n done?: (result: ExportResult) => void\n ): void {\n for (const span of spans) {\n console.dir(this._exportInfo(span), { depth: 3 });\n }\n if (done) {\n return done({ code: ExportResultCode.SUCCESS });\n }\n }\n}\n"]}
import type { SpanExporter } from './SpanExporter';
import type { ReadableSpan } from './ReadableSpan';
import type { ExportResult } from '@opentelemetry/core';
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
export declare class InMemorySpanExporter implements SpanExporter {
private _finishedSpans;
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
protected _stopped: boolean;
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
shutdown(): Promise<void>;
/**
* Exports any pending spans in the exporter
*/
forceFlush(): Promise<void>;
reset(): void;
getFinishedSpans(): ReadableSpan[];
}
//# sourceMappingURL=InMemorySpanExporter.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { ExportResultCode } from '@opentelemetry/core';
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
export class InMemorySpanExporter {
_finishedSpans = [];
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
_stopped = false;
export(spans, resultCallback) {
if (this._stopped)
return resultCallback({
code: ExportResultCode.FAILED,
error: new Error('Exporter has been stopped'),
});
this._finishedSpans.push(...spans);
setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);
}
shutdown() {
this._stopped = true;
this._finishedSpans = [];
return this.forceFlush();
}
/**
* Exports any pending spans in the exporter
*/
forceFlush() {
return Promise.resolve();
}
reset() {
this._finishedSpans = [];
}
getFinishedSpans() {
return this._finishedSpans;
}
}
//# sourceMappingURL=InMemorySpanExporter.js.map
{"version":3,"file":"InMemorySpanExporter.js","sourceRoot":"","sources":["../../../src/export/InMemorySpanExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;;;GAIG;AACH,MAAM,OAAO,oBAAoB;IACvB,cAAc,GAAmB,EAAE,CAAC;IAC5C;;;OAGG;IACO,QAAQ,GAAG,KAAK,CAAC;IAE3B,MAAM,CACJ,KAAqB,EACrB,cAA8C;QAE9C,IAAI,IAAI,CAAC,QAAQ;YACf,OAAO,cAAc,CAAC;gBACpB,IAAI,EAAE,gBAAgB,CAAC,MAAM;gBAC7B,KAAK,EAAE,IAAI,KAAK,CAAC,2BAA2B,CAAC;aAC9C,CAAC,CAAC;QACL,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;QAEnC,UAAU,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1E,CAAC;IAED,QAAQ;QACN,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;IAC3B,CAAC;IAED,gBAAgB;QACd,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from './SpanExporter';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\n\n/**\n * This class can be used for testing purposes. It stores the exported spans\n * in a list in memory that can be retrieved using the `getFinishedSpans()`\n * method.\n */\nexport class InMemorySpanExporter implements SpanExporter {\n private _finishedSpans: ReadableSpan[] = [];\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported spans will not be stored in-memory.\n */\n protected _stopped = false;\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._stopped)\n return resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n this._finishedSpans.push(...spans);\n\n setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);\n }\n\n shutdown(): Promise<void> {\n this._stopped = true;\n this._finishedSpans = [];\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n reset(): void {\n this._finishedSpans = [];\n }\n\n getFinishedSpans(): ReadableSpan[] {\n return this._finishedSpans;\n }\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './ReadableSpan';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
/** No-op implementation of SpanProcessor */
export declare class NoopSpanProcessor implements SpanProcessor {
onStart(_span: Span, _context: Context): void;
onEnd(_span: ReadableSpan): void;
shutdown(): Promise<void>;
forceFlush(): Promise<void>;
}
//# sourceMappingURL=NoopSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/** No-op implementation of SpanProcessor */
export class NoopSpanProcessor {
onStart(_span, _context) { }
onEnd(_span) { }
shutdown() {
return Promise.resolve();
}
forceFlush() {
return Promise.resolve();
}
}
//# sourceMappingURL=NoopSpanProcessor.js.map
{"version":3,"file":"NoopSpanProcessor.js","sourceRoot":"","sources":["../../../src/export/NoopSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,4CAA4C;AAC5C,MAAM,OAAO,iBAAiB;IAC5B,OAAO,CAAC,KAAW,EAAE,QAAiB,IAAS,CAAC;IAChD,KAAK,CAAC,KAAmB,IAAS,CAAC;IACnC,QAAQ;QACN,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IACD,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\n\n/** No-op implementation of SpanProcessor */\nexport class NoopSpanProcessor implements SpanProcessor {\n onStart(_span: Span, _context: Context): void {}\n onEnd(_span: ReadableSpan): void {}\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n"]}
import type { SpanKind, SpanStatus, Attributes, HrTime, Link, SpanContext } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { TimedEvent } from '../TimedEvent';
export interface ReadableSpan {
readonly name: string;
readonly kind: SpanKind;
readonly spanContext: () => SpanContext;
readonly parentSpanContext?: SpanContext;
readonly startTime: HrTime;
readonly endTime: HrTime;
readonly status: SpanStatus;
readonly attributes: Attributes;
readonly links: Link[];
readonly events: TimedEvent[];
readonly duration: HrTime;
readonly ended: boolean;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
readonly droppedAttributesCount: number;
readonly droppedEventsCount: number;
readonly droppedLinksCount: number;
}
//# sourceMappingURL=ReadableSpan.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=ReadableSpan.js.map
{"version":3,"file":"ReadableSpan.js","sourceRoot":"","sources":["../../../src/export/ReadableSpan.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n SpanKind,\n SpanStatus,\n Attributes,\n HrTime,\n Link,\n SpanContext,\n} from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { TimedEvent } from '../TimedEvent';\n\nexport interface ReadableSpan {\n readonly name: string;\n readonly kind: SpanKind;\n readonly spanContext: () => SpanContext;\n readonly parentSpanContext?: SpanContext;\n readonly startTime: HrTime;\n readonly endTime: HrTime;\n readonly status: SpanStatus;\n readonly attributes: Attributes;\n readonly links: Link[];\n readonly events: TimedEvent[];\n readonly duration: HrTime;\n readonly ended: boolean;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n readonly droppedAttributesCount: number;\n readonly droppedEventsCount: number;\n readonly droppedLinksCount: number;\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
import type { ReadableSpan } from './ReadableSpan';
import type { SpanExporter } from './SpanExporter';
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
export declare class SimpleSpanProcessor implements SpanProcessor {
private readonly _exporter;
private _shutdownOnce;
private _pendingExports;
constructor(exporter: SpanExporter);
forceFlush(): Promise<void>;
onStart(_span: Span, _parentContext: Context): void;
onEnd(span: ReadableSpan): void;
private _doExport;
shutdown(): Promise<void>;
private _shutdown;
}
//# sourceMappingURL=SimpleSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { TraceFlags } from '@opentelemetry/api';
import { internal, ExportResultCode, globalErrorHandler, BindOnceFuture, } from '@opentelemetry/core';
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
export class SimpleSpanProcessor {
_exporter;
_shutdownOnce;
_pendingExports;
constructor(exporter) {
this._exporter = exporter;
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
this._pendingExports = new Set();
}
async forceFlush() {
await Promise.all(Array.from(this._pendingExports));
if (this._exporter.forceFlush) {
await this._exporter.forceFlush();
}
}
onStart(_span, _parentContext) { }
onEnd(span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {
return;
}
const pendingExport = this._doExport(span).catch(err => globalErrorHandler(err));
// Enqueue this export to the pending list so it can be flushed by the user.
this._pendingExports.add(pendingExport);
void pendingExport.finally(() => this._pendingExports.delete(pendingExport));
}
async _doExport(span) {
if (span.resource.asyncAttributesPending) {
// Ensure resource is fully resolved before exporting.
await span.resource.waitForAsyncAttributes?.();
}
const result = await internal._export(this._exporter, [span]);
if (result.code !== ExportResultCode.SUCCESS) {
throw (result.error ??
new Error(`SimpleSpanProcessor: span export failed (status ${result})`));
}
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return this._exporter.shutdown();
}
}
//# sourceMappingURL=SimpleSpanProcessor.js.map
{"version":3,"file":"SimpleSpanProcessor.js","sourceRoot":"","sources":["../../../src/export/S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AK,aAAa,CAAC,OAAO,CAAC,GAAG,EAAE,CAC9B,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,aAAa,CAAC,CAC3C,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,SAAS,CAAC,IAAkB;QACxC,IAAI,IAAI,CAAC,QAAQ,CAAC,sBAAsB,EAAE;YACxC,sDAAsD;YACtD,MAAM,IAAI,CAAC,QAAQ,CAAC,sBAAsB,EAAE,EAAE,CAAC;SAChD;QAED,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QAC9D,IAAI,MAAM,CAAC,IAAI,KAAK,gBAAgB,CAAC,OAAO,EAAE;YAC5C,MAAM,CACJ,MAAM,CAAC,KAAK;gBACZ,IAAI,KAAK,CAAC,mDAAmD,MAAM,GAAG,CAAC,CACxE,CAAC;SACH;IACH,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;IACnC,CAAC;IAEO,SAAS;QACf,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IACnC,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { TraceFlags } from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n BindOnceFuture,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * An implementation of the {@link SpanProcessor} that converts the {@link Span}\n * to {@link ReadableSpan} and passes it to the configured exporter.\n *\n * Only spans that are sampled are converted.\n *\n * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.\n */\nexport class SimpleSpanProcessor implements SpanProcessor {\n private readonly _exporter: SpanExporter;\n private _shutdownOnce: BindOnceFuture<void>;\n private _pendingExports: Set<Promise<void>>;\n\n constructor(exporter: SpanExporter) {\n this._exporter = exporter;\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._pendingExports = new Set<Promise<void>>();\n }\n\n async forceFlush(): Promise<void> {\n await Promise.all(Array.from(this._pendingExports));\n if (this._exporter.forceFlush) {\n await this._exporter.forceFlush();\n }\n }\n\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n const pendingExport = this._doExport(span).catch(err =>\n globalErrorHandler(err)\n );\n // Enqueue this export to the pending list so it can be flushed by the user.\n this._pendingExports.add(pendingExport);\n void pendingExport.finally(() =>\n this._pendingExports.delete(pendingExport)\n );\n }\n\n private async _doExport(span: ReadableSpan): Promise<void> {\n if (span.resource.asyncAttributesPending) {\n // Ensure resource is fully resolved before exporting.\n await span.resource.waitForAsyncAttributes?.();\n }\n\n const result = await internal._export(this._exporter, [span]);\n if (result.code !== ExportResultCode.SUCCESS) {\n throw (\n result.error ??\n new Error(`SimpleSpanProcessor: span export failed (status ${result})`)\n );\n }\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n return this._exporter.shutdown();\n }\n}\n"]}
import type { ExportResult } from '@opentelemetry/core';
import type { ReadableSpan } from './ReadableSpan';
/**
* An interface that allows different tracing services to export recorded data
* for sampled spans in their own format.
*
* To export data this MUST be register to the Tracer SDK using a optional
* config.
*/
export interface SpanExporter {
/**
* Called to export sampled {@link ReadableSpan}s.
* @param spans the list of sampled Spans to be exported.
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/** Stops the exporter. */
shutdown(): Promise<void>;
/** Immediately export all spans */
forceFlush?(): Promise<void>;
}
//# sourceMappingURL=SpanExporter.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=SpanExporter.js.map
{"version":3,"file":"SpanExporter.js","sourceRoot":"","sources":["../../../src/export/SpanExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport type { ReadableSpan } from './ReadableSpan';\n\n/**\n * An interface that allows different tracing services to export recorded data\n * for sampled spans in their own format.\n *\n * To export data this MUST be register to the Tracer SDK using a optional\n * config.\n */\nexport interface SpanExporter {\n /**\n * Called to export sampled {@link ReadableSpan}s.\n * @param spans the list of sampled Spans to be exported.\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void;\n\n /** Stops the exporter. */\n shutdown(): Promise<void>;\n\n /** Immediately export all spans */\n forceFlush?(): Promise<void>;\n}\n"]}
/** IdGenerator provides an interface for generating Trace Id and Span Id */
export interface IdGenerator {
/** Returns a trace ID composed of 32 lowercase hex characters. */
generateTraceId(): string;
/** Returns a span ID composed of 16 lowercase hex characters. */
generateSpanId(): string;
}
//# sourceMappingURL=IdGenerator.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=IdGenerator.js.map
{"version":3,"file":"IdGenerator.js","sourceRoot":"","sources":["../../src/IdGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/** IdGenerator provides an interface for generating Trace Id and Span Id */\nexport interface IdGenerator {\n /** Returns a trace ID composed of 32 lowercase hex characters. */\n generateTraceId(): string;\n /** Returns a span ID composed of 16 lowercase hex characters. */\n generateSpanId(): string;\n}\n"]}
export { BasicTracerProvider } from './BasicTracerProvider';
export { BatchSpanProcessor, RandomIdGenerator } from './platform';
export { ConsoleSpanExporter } from './export/ConsoleSpanExporter';
export { InMemorySpanExporter } from './export/InMemorySpanExporter';
export type { ReadableSpan } from './export/ReadableSpan';
export { SimpleSpanProcessor } from './export/SimpleSpanProcessor';
export type { SpanExporter } from './export/SpanExporter';
export { NoopSpanProcessor } from './export/NoopSpanProcessor';
export { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
export { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
export { ParentBasedSampler } from './sampler/ParentBasedSampler';
export { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
export { SamplingDecision } from './Sampler';
export type { Sampler, SamplingResult } from './Sampler';
export type { Span } from './Span';
export type { SpanProcessor } from './SpanProcessor';
export type { TimedEvent } from './TimedEvent';
export type { BatchSpanProcessorBrowserConfig, BufferConfig, GeneralLimits, SDKRegistrationConfig, SpanLimits, TracerConfig, } from './types';
export type { IdGenerator } from './IdGenerator';
//# sourceMappingURL=index.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BasicTracerProvider } from './BasicTracerProvider';
export { BatchSpanProcessor, RandomIdGenerator } from './platform';
export { ConsoleSpanExporter } from './export/ConsoleSpanExporter';
export { InMemorySpanExporter } from './export/InMemorySpanExporter';
export { SimpleSpanProcessor } from './export/SimpleSpanProcessor';
export { NoopSpanProcessor } from './export/NoopSpanProcessor';
export { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
export { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
export { ParentBasedSampler } from './sampler/ParentBasedSampler';
export { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
export { SamplingDecision } from './Sampler';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BasicTracerProvider } from './BasicTracerProvider';\nexport { BatchSpanProcessor, RandomIdGenerator } from './platform';\nexport { ConsoleSpanExporter } from './export/ConsoleSpanExporter';\nexport { InMemorySpanExporter } from './export/InMemorySpanExporter';\nexport type { ReadableSpan } from './export/ReadableSpan';\nexport { SimpleSpanProcessor } from './export/SimpleSpanProcessor';\nexport type { SpanExporter } from './export/SpanExporter';\nexport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nexport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nexport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nexport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nexport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\nexport { SamplingDecision } from './Sampler';\nexport type { Sampler, SamplingResult } from './Sampler';\nexport type { Span } from './Span';\nexport type { SpanProcessor } from './SpanProcessor';\nexport type { TimedEvent } from './TimedEvent';\nexport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n GeneralLimits,\n SDKRegistrationConfig,\n SpanLimits,\n TracerConfig,\n} from './types';\nexport type { IdGenerator } from './IdGenerator';\n"]}
import type { Attributes } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
/**
* Well-known symbol used by Node.js `util.inspect` (and `console.*`) to
* render an object via a custom representation. Defined as a global Symbol
* so it works without importing from `node:util`, keeping this module safe
* for browser builds (where the symbol is simply never looked up).
*/
export declare const inspectCustom: unique symbol;
/**
* Collect a Resource's settled attributes without touching the
* `attributes` getter, which emits diag.error/debug entries when async
* attribute detectors are still pending. Promise-like (unsettled)
* entries are silently skipped so logging a Span/Tracer/Provider during
* startup doesn't recurse through the diag pipeline.
*/
export declare function settledResourceAttributes(resource: Resource): Attributes;
export type InspectFn = (value: unknown, options: unknown) => string;
export interface InspectStylizeOptions {
depth?: number | null;
stylize?: (text: string, styleType: string) => string;
}
/**
* Build a class-tagged inspect representation. Returns a stub like
* `[ClassName]` once the recursion budget is exhausted, otherwise returns
* `ClassName <inspected payload>` so nested fields keep proper coloring,
* indentation, and depth handling. In environments that don't supply an
* `inspect` callback (e.g. browsers), falls back to returning the raw
* payload object.
*/
export declare function formatInspect(className: string, payload: object, depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
//# sourceMappingURL=inspect.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Well-known symbol used by Node.js `util.inspect` (and `console.*`) to
* render an object via a custom representation. Defined as a global Symbol
* so it works without importing from `node:util`, keeping this module safe
* for browser builds (where the symbol is simply never looked up).
*/
export const inspectCustom = Symbol.for('nodejs.util.inspect.custom');
/**
* Collect a Resource's settled attributes without touching the
* `attributes` getter, which emits diag.error/debug entries when async
* attribute detectors are still pending. Promise-like (unsettled)
* entries are silently skipped so logging a Span/Tracer/Provider during
* startup doesn't recurse through the diag pipeline.
*/
export function settledResourceAttributes(resource) {
const attrs = {};
for (const [k, v] of resource.getRawAttributes()) {
if (typeof v?.then === 'function') {
continue;
}
if (v != null) {
attrs[k] ??= v;
}
}
return attrs;
}
/**
* Build a class-tagged inspect representation. Returns a stub like
* `[ClassName]` once the recursion budget is exhausted, otherwise returns
* `ClassName <inspected payload>` so nested fields keep proper coloring,
* indentation, and depth handling. In environments that don't supply an
* `inspect` callback (e.g. browsers), falls back to returning the raw
* payload object.
*/
export function formatInspect(className, payload, depth, options, inspect) {
if (typeof depth === 'number' && depth < 0) {
const tag = `[${className}]`;
return options?.stylize ? options.stylize(tag, 'special') : tag;
}
if (typeof inspect !== 'function' || !options) {
return payload;
}
const childOptions = {
...options,
depth: options.depth == null ? options.depth : options.depth - 1,
};
return `${className} ${inspect(payload, childOptions)}`;
}
//# sourceMappingURL=inspect.js.map
{"version":3,"file":"inspect.js","sourceRoot":"","sources":["../../src/inspect.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CAAC,QAAkB;IAC1D,MAAM,KAAK,GAAe,EAAE,CAAC;IAC7B,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,QAAQ,CAAC,gBAAgB,EAAE,EAAE;QAChD,IAAI,OAAQ,CAAmC,EAAE,IAAI,KAAK,UAAU,EAAE;YACpE,SAAS;SACV;QACD,IAAI,CAAC,IAAI,IAAI,EAAE;YACb,KAAK,CAAC,CAAC,CAAC,KAAK,CAAmB,CAAC;SAClC;KACF;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AASD;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAC3B,SAAiB,EACjB,OAAe,EACf,KAAa,EACb,OAA0C,EAC1C,OAA8B;IAE9B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,GAAG,CAAC,EAAE;QAC1C,MAAM,GAAG,GAAG,IAAI,SAAS,GAAG,CAAC;QAC7B,OAAO,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;KACjE;IACD,IAAI,OAAO,OAAO,KAAK,UAAU,IAAI,CAAC,OAAO,EAAE;QAC7C,OAAO,OAAO,CAAC;KAChB;IACD,MAAM,YAAY,GAAG;QACnB,GAAG,OAAO;QACV,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,GAAG,CAAC;KACjE,CAAC;IACF,OAAO,GAAG,SAAS,IAAI,OAAO,CAAC,OAAO,EAAE,YAAY,CAAC,EAAE,CAAC;AAC1D,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\n\n/**\n * Well-known symbol used by Node.js `util.inspect` (and `console.*`) to\n * render an object via a custom representation. Defined as a global Symbol\n * so it works without importing from `node:util`, keeping this module safe\n * for browser builds (where the symbol is simply never looked up).\n */\nexport const inspectCustom = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * Collect a Resource's settled attributes without touching the\n * `attributes` getter, which emits diag.error/debug entries when async\n * attribute detectors are still pending. Promise-like (unsettled)\n * entries are silently skipped so logging a Span/Tracer/Provider during\n * startup doesn't recurse through the diag pipeline.\n */\nexport function settledResourceAttributes(resource: Resource): Attributes {\n const attrs: Attributes = {};\n for (const [k, v] of resource.getRawAttributes()) {\n if (typeof (v as Partial<PromiseLike<unknown>>)?.then === 'function') {\n continue;\n }\n if (v != null) {\n attrs[k] ??= v as AttributeValue;\n }\n }\n return attrs;\n}\n\nexport type InspectFn = (value: unknown, options: unknown) => string;\n\nexport interface InspectStylizeOptions {\n depth?: number | null;\n stylize?: (text: string, styleType: string) => string;\n}\n\n/**\n * Build a class-tagged inspect representation. Returns a stub like\n * `[ClassName]` once the recursion budget is exhausted, otherwise returns\n * `ClassName <inspected payload>` so nested fields keep proper coloring,\n * indentation, and depth handling. In environments that don't supply an\n * `inspect` callback (e.g. browsers), falls back to returning the raw\n * payload object.\n */\nexport function formatInspect(\n className: string,\n payload: object,\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n): unknown {\n if (typeof depth === 'number' && depth < 0) {\n const tag = `[${className}]`;\n return options?.stylize ? options.stylize(tag, 'special') : tag;\n }\n if (typeof inspect !== 'function' || !options) {\n return payload;\n }\n const childOptions = {\n ...options,\n depth: options.depth == null ? options.depth : options.depth - 1,\n };\n return `${className} ${inspect(payload, childOptions)}`;\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './export/ReadableSpan';
import type { Span } from './Span';
import type { SpanProcessor } from './SpanProcessor';
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
export declare class MultiSpanProcessor implements SpanProcessor {
private readonly _spanProcessors;
constructor(spanProcessors: SpanProcessor[]);
forceFlush(): Promise<void>;
onStart(span: Span, context: Context): void;
onEnding(span: Span): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
}
//# sourceMappingURL=MultiSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { globalErrorHandler } from '@opentelemetry/core';
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
export class MultiSpanProcessor {
_spanProcessors;
constructor(spanProcessors) {
this._spanProcessors = spanProcessors;
}
forceFlush() {
const promises = [];
for (const spanProcessor of this._spanProcessors) {
promises.push(spanProcessor.forceFlush());
}
return new Promise(resolve => {
Promise.all(promises)
.then(() => {
resolve();
})
.catch(error => {
globalErrorHandler(error || new Error('MultiSpanProcessor: forceFlush failed'));
resolve();
});
});
}
onStart(span, context) {
for (const spanProcessor of this._spanProcessors) {
spanProcessor.onStart(span, context);
}
}
onEnding(span) {
for (const spanProcessor of this._spanProcessors) {
if (spanProcessor.onEnding) {
spanProcessor.onEnding(span);
}
}
}
onEnd(span) {
for (const spanProcessor of this._spanProcessors) {
spanProcessor.onEnd(span);
}
}
shutdown() {
const promises = [];
for (const spanProcessor of this._spanProcessors) {
promises.push(spanProcessor.shutdown());
}
return new Promise((resolve, reject) => {
Promise.all(promises).then(() => {
resolve();
}, reject);
});
}
}
//# sourceMappingURL=MultiSpanProcessor.js.map
{"version":3,"file":"MultiSpanProcessor.js","sourceRoot":"","sources":["../../src/MultiSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAKzD;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IACZ,eAAe,CAAkB;IAClD,YAAY,cAA+B;QACzC,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;IACxC,CAAC;IAED,UAAU;QACR,MAAM,QAAQ,GAAoB,EAAE,CAAC;QAErC,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC,CAAC;SAC3C;QACD,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YAC3B,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;iBAClB,IAAI,CAAC,GAAG,EAAE;gBACT,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC;iBACD,KAAK,CAAC,KAAK,CAAC,EAAE;gBACb,kBAAkB,CAChB,KAAK,IAAI,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAC5D,CAAC;gBACF,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,CAAC,IAAU,EAAE,OAAgB;QAClC,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,aAAa,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;SACtC;IACH,CAAC;IAED,QAAQ,CAAC,IAAU;QACjB,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,IAAI,aAAa,CAAC,QAAQ,EAAE;gBAC1B,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;aAC9B;SACF;IACH,CAAC;IAED,KAAK,CAAC,IAAkB;QACtB,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SAC3B;IACH,CAAC;IAED,QAAQ;QACN,MAAM,QAAQ,GAAoB,EAAE,CAAC;QAErC,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC,CAAC;SACzC;QACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;gBAC9B,OAAO,EAAE,CAAC;YACZ,CAAC,EAAE,MAAM,CAAC,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n"]}
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import type { SpanExporter } from '../../../export/SpanExporter';
import type { BatchSpanProcessorBrowserConfig } from '../../../types';
export declare class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {
private _visibilityChangeListener?;
private _pageHideListener?;
constructor(_exporter: SpanExporter, config?: BatchSpanProcessorBrowserConfig);
private onInit;
protected onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import { globalErrorHandler } from '@opentelemetry/core';
export class BatchSpanProcessor extends BatchSpanProcessorBase {
_visibilityChangeListener;
_pageHideListener;
constructor(_exporter, config) {
super(_exporter, config);
this.onInit(config);
}
onInit(config) {
if (config?.disableAutoFlushOnDocumentHide !== true &&
typeof document !== 'undefined') {
this._visibilityChangeListener = () => {
if (document.visibilityState === 'hidden') {
this.forceFlush().catch(error => {
globalErrorHandler(error);
});
}
};
this._pageHideListener = () => {
this.forceFlush().catch(error => {
globalErrorHandler(error);
});
};
document.addEventListener('visibilitychange', this._visibilityChangeListener);
// use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769
document.addEventListener('pagehide', this._pageHideListener);
}
}
onShutdown() {
if (typeof document !== 'undefined') {
if (this._visibilityChangeListener) {
document.removeEventListener('visibilitychange', this._visibilityChangeListener);
}
if (this._pageHideListener) {
document.removeEventListener('pagehide', this._pageHideListener);
}
}
}
}
//# sourceMappingURL=BatchSpanProcessor.js.map
{"version":3,"file":"BatchSpanProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/browser/export/BatchSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAGhF,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAEzD,MAAM,OAAO,kBAAmB,SAAQ,sBAAuD;IACrF,yBAAyB,CAAc;IACvC,iBAAiB,CAAc;IAEvC,YACE,SAAuB,EACvB,MAAwC;QAExC,KAAK,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QACzB,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IAEO,MAAM,CAAC,MAAwC;QACrD,IACE,MAAM,EAAE,8BAA8B,KAAK,IAAI;YAC/C,OAAO,QAAQ,KAAK,WAAW,EAC/B;YACA,IAAI,CAAC,yBAAyB,GAAG,GAAG,EAAE;gBACpC,IAAI,QAAQ,CAAC,eAAe,KAAK,QAAQ,EAAE;oBACzC,IAAI,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;wBAC9B,kBAAkB,CAAC,KAAK,CAAC,CAAC;oBAC5B,CAAC,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC;YACF,IAAI,CAAC,iBAAiB,GAAG,GAAG,EAAE;gBAC5B,IAAI,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;oBAC9B,kBAAkB,CAAC,KAAK,CAAC,CAAC;gBAC5B,CAAC,CAAC,CAAC;YACL,CAAC,CAAC;YACF,QAAQ,CAAC,gBAAgB,CACvB,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;YAEF,oGAAoG;YACpG,QAAQ,CAAC,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;SAC/D;IACH,CAAC;IAES,UAAU;QAClB,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;YACnC,IAAI,IAAI,CAAC,yBAAyB,EAAE;gBAClC,QAAQ,CAAC,mBAAmB,CAC1B,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;aACH;YACD,IAAI,IAAI,CAAC,iBAAiB,EAAE;gBAC1B,QAAQ,CAAC,mBAAmB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;aAClE;SACF;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { SpanExporter } from '../../../export/SpanExporter';\nimport type { BatchSpanProcessorBrowserConfig } from '../../../types';\nimport { globalErrorHandler } from '@opentelemetry/core';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {\n private _visibilityChangeListener?: () => void;\n private _pageHideListener?: () => void;\n\n constructor(\n _exporter: SpanExporter,\n config?: BatchSpanProcessorBrowserConfig\n ) {\n super(_exporter, config);\n this.onInit(config);\n }\n\n private onInit(config?: BatchSpanProcessorBrowserConfig): void {\n if (\n config?.disableAutoFlushOnDocumentHide !== true &&\n typeof document !== 'undefined'\n ) {\n this._visibilityChangeListener = () => {\n if (document.visibilityState === 'hidden') {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n }\n };\n this._pageHideListener = () => {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n };\n document.addEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n\n // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769\n document.addEventListener('pagehide', this._pageHideListener);\n }\n }\n\n protected onShutdown(): void {\n if (typeof document !== 'undefined') {\n if (this._visibilityChangeListener) {\n document.removeEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n }\n if (this._pageHideListener) {\n document.removeEventListener('pagehide', this._pageHideListener);\n }\n }\n }\n}\n"]}
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n"]}
import type { IdGenerator } from '../../IdGenerator';
export declare class RandomIdGenerator implements IdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId(): string;
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId(): string;
}
//# sourceMappingURL=RandomIdGenerator.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
const TRACE_ID_BYTES = 16;
const SPAN_ID_BYTES = 8;
const TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);
const SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);
// Byte-to-hex lookup is faster than toString(16) in browsers
const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
* Fills buffer with random bytes, ensuring at least one is non-zero
* per W3C Trace Context spec.
*/
function randomFill(buf) {
for (let i = 0; i < buf.length; i++) {
buf[i] = (Math.random() * 256) >>> 0;
}
// Ensure non-zero
for (let i = 0; i < buf.length; i++) {
if (buf[i] > 0)
return;
}
buf[buf.length - 1] = 1;
}
function toHex(buf) {
let hex = '';
for (let i = 0; i < buf.length; i++) {
hex += HEX[buf[i]];
}
return hex;
}
export class RandomIdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId() {
randomFill(TRACE_BUFFER);
return toHex(TRACE_BUFFER);
}
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId() {
randomFill(SPAN_BUFFER);
return toHex(SPAN_BUFFER);
}
}
//# sourceMappingURL=RandomIdGenerator.js.map
{"version":3,"file":"RandomIdGenerator.js","sourceRoot":"","sources":["../../../../src/platform/browser/RandomIdGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,cAAc,GAAG,EAAE,CAAC;AAC1B,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,MAAM,YAAY,GAAG,IAAI,UAAU,CAAC,cAAc,CAAC,CAAC;AACpD,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC,aAAa,CAAC,CAAC;AAElD,6DAA6D;AAC7D,MAAM,GAAG,GAAa,KAAK,CAAC,IAAI,C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right The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst TRACE_ID_BYTES = 16;\nconst SPAN_ID_BYTES = 8;\n\nconst TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);\nconst SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);\n\n// Byte-to-hex lookup is faster than toString(16) in browsers\nconst HEX: string[] = Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Fills buffer with random bytes, ensuring at least one is non-zero\n * per W3C Trace Context spec.\n */\nfunction randomFill(buf: Uint8Array): void {\n for (let i = 0; i < buf.length; i++) {\n buf[i] = (Math.random() * 256) >>> 0;\n }\n // Ensure non-zero\n for (let i = 0; i < buf.length; i++) {\n if (buf[i] > 0) return;\n }\n buf[buf.length - 1] = 1;\n}\n\nfunction toHex(buf: Uint8Array): string {\n let hex = '';\n for (let i = 0; i < buf.length; i++) {\n hex += HEX[buf[i]];\n }\n return hex;\n}\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId(): string {\n randomFill(TRACE_BUFFER);\n return toHex(TRACE_BUFFER);\n }\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId(): string {\n randomFill(SPAN_BUFFER);\n return toHex(SPAN_BUFFER);\n }\n}\n"]}
export { BatchSpanProcessor, RandomIdGenerator } from './node';
//# sourceMappingURL=index.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchSpanProcessor, RandomIdGenerator } from './node';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor, RandomIdGenerator } from './node';\n"]}
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import type { BufferConfig } from '../../../types';
export declare class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {
protected onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
export class BatchSpanProcessor extends BatchSpanProcessorBase {
onShutdown() { }
}
//# sourceMappingURL=BatchSpanProcessor.js.map
{"version":3,"file":"BatchSpanProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/node/export/BatchSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAGhF,MAAM,OAAO,kBAAmB,SAAQ,sBAAoC;IAChE,UAAU,KAAU,CAAC;CAChC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n"]}
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n"]}
import type { IdGenerator } from '../../IdGenerator';
export declare class RandomIdGenerator implements IdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId: () => string;
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId: () => string;
}
//# sourceMappingURL=RandomIdGenerator.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
const SPAN_ID_BYTES = 8;
const TRACE_ID_BYTES = 16;
export class RandomIdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId = getIdGenerator(TRACE_ID_BYTES);
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId = getIdGenerator(SPAN_ID_BYTES);
}
const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
function getIdGenerator(bytes) {
return function generateId() {
for (let i = 0; i < bytes / 4; i++) {
// unsigned right shift drops decimal part of the number
// it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE
SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);
}
// If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated
for (let i = 0; i < bytes; i++) {
if (SHARED_BUFFER[i] > 0) {
break;
}
else if (i === bytes - 1) {
SHARED_BUFFER[bytes - 1] = 1;
}
}
return SHARED_BUFFER.toString('hex', 0, bytes);
};
}
//# sourceMappingURL=RandomIdGenerator.js.map
{"version":3,"file":"RandomIdGenerator.js","sourceRoot":"","sources":["../../../../src/platform/node/RandomIdGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,cAAc,GAAG,EAAE,CAAC;AAE1B,MAAM,OAAO,iBAAiB;IAC5B;;;OAGG;IACH,eAAe,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;IAEjD;;;OAGG;IACH,cAAc,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;CAChD;AAED,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;AACzD,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,SAAS,UAAU;QACxB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YAClC,wDAAwD;YACxD,gIAAgI;YAChI,aAAa,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;SACrE;QAED,sFAAsF;QACtF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YAC9B,IAAI,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE;gBACxB,MAAM;aACP;iBAAM,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE;gBAC1B,aAAa,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;aAC9B;SACF;QAED,OAAO,aAAa,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n"]}
import type { Context, Link, Attributes, SpanKind, TraceState } from '@opentelemetry/api';
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
export declare enum SamplingDecision {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
NOT_RECORD = 0,
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
RECORD = 1,
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
RECORD_AND_SAMPLED = 2
}
/**
* A sampling result contains a decision for a {@link Span} and additional
* attributes the sampler would like to added to the Span.
*/
export interface SamplingResult {
/**
* A sampling decision, refer to {@link SamplingDecision} for details.
*/
decision: SamplingDecision;
/**
* The list of attributes returned by SamplingResult MUST be immutable.
* Caller may call {@link Sampler}.shouldSample any number of times and
* can safely cache the returned value.
*/
attributes?: Readonly<Attributes>;
/**
* A {@link TraceState} that will be associated with the {@link Span} through
* the new {@link SpanContext}. Samplers SHOULD return the TraceState from
* the passed-in {@link Context} if they do not intend to change it. Leaving
* the value undefined will also leave the TraceState unchanged.
*/
traceState?: TraceState;
}
/**
* This interface represent a sampler. Sampling is a mechanism to control the
* noise and overhead introduced by OpenTelemetry by reducing the number of
* samples of traces collected and sent to the backend.
*/
export interface Sampler {
/**
* Checks whether span needs to be created and tracked.
*
* @param context Parent Context which may contain a span.
* @param traceId of the span to be created. It can be different from the
* traceId in the {@link SpanContext}. Typically in situations when the
* span to be created starts a new trace.
* @param spanName of the span to be created.
* @param spanKind of the span to be created.
* @param attributes Initial set of Attributes for the Span being constructed.
* @param links Collection of links that will be associated with the Span to
* be created. Typically useful for batch operations.
* @returns a {@link SamplingResult}.
*/
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: Attributes, links: Link[]): SamplingResult;
/** Returns the sampler name or short description with the configuration. */
toString(): string;
}
//# sourceMappingURL=Sampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
export var SamplingDecision;
(function (SamplingDecision) {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
})(SamplingDecision || (SamplingDecision = {}));
//# sourceMappingURL=Sampler.js.map
{"version":3,"file":"Sampler.js","sourceRoot":"","sources":["../../src/Sampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAUH;;;GAGG;AACH,MAAM,CAAN,IAAY,gBAgBX;AAhBD,WAAY,gBAAgB;IAC1B;;;OAGG;IACH,mEAAU,CAAA;IACV;;;OAGG;IACH,2DAAM,CAAA;IACN;;;OAGG;IACH,mFAAkB,CAAA;AACpB,CAAC,EAhBW,gBAAgB,KAAhB,gBAAgB,QAgB3B","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples no traces. */
export declare class AlwaysOffSampler implements Sampler {
shouldSample(): SamplingResult;
toString(): string;
}
//# sourceMappingURL=AlwaysOffSampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SamplingDecision } from '../Sampler';
/** Sampler that samples no traces. */
export class AlwaysOffSampler {
shouldSample() {
return {
decision: SamplingDecision.NOT_RECORD,
};
}
toString() {
return 'AlwaysOffSampler';
}
}
//# sourceMappingURL=AlwaysOffSampler.js.map
{"version":3,"file":"AlwaysOffSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysOffSampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,sCAAsC;AACtC,MAAM,OAAO,gBAAgB;IAC3B,YAAY;QACV,OAAO;YACL,QAAQ,EAAE,gBAAgB,CAAC,UAAU;SACtC,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples all traces. */
export declare class AlwaysOnSampler implements Sampler {
shouldSample(): SamplingResult;
toString(): string;
}
//# sourceMappingURL=AlwaysOnSampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SamplingDecision } from '../Sampler';
/** Sampler that samples all traces. */
export class AlwaysOnSampler {
shouldSample() {
return {
decision: SamplingDecision.RECORD_AND_SAMPLED,
};
}
toString() {
return 'AlwaysOnSampler';
}
}
//# sourceMappingURL=AlwaysOnSampler.js.map
{"version":3,"file":"AlwaysOnSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysOnSampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,uCAAuC;AACvC,MAAM,OAAO,eAAe;IAC1B,YAAY;QACV,OAAO;YACL,QAAQ,EAAE,gBAAgB,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,iBAAiB,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n"]}
import type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';
import type { Sampler, SamplingResult } from '../Sampler';
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
export declare class ParentBasedSampler implements Sampler {
private _root;
private _remoteParentSampled;
private _remoteParentNotSampled;
private _localParentSampled;
private _localParentNotSampled;
constructor(config: ParentBasedSamplerConfig);
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: Attributes, links: Link[]): SamplingResult;
toString(): string;
}
interface ParentBasedSamplerConfig {
/** Sampler called for spans with no parent */
root: Sampler;
/** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */
remoteParentSampled?: Sampler;
/** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */
remoteParentNotSampled?: Sampler;
/** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */
localParentSampled?: Sampler;
/** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */
localParentNotSampled?: Sampler;
}
export {};
//# sourceMappingURL=ParentBasedSampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';
import { globalErrorHandler } from '@opentelemetry/core';
import { AlwaysOffSampler } from './AlwaysOffSampler';
import { AlwaysOnSampler } from './AlwaysOnSampler';
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
export class ParentBasedSampler {
_root;
_remoteParentSampled;
_remoteParentNotSampled;
_localParentSampled;
_localParentNotSampled;
constructor(config) {
this._root = config.root;
if (!this._root) {
globalErrorHandler(new Error('ParentBasedSampler must have a root sampler configured'));
this._root = new AlwaysOnSampler();
}
this._remoteParentSampled =
config.remoteParentSampled ?? new AlwaysOnSampler();
this._remoteParentNotSampled =
config.remoteParentNotSampled ?? new AlwaysOffSampler();
this._localParentSampled =
config.localParentSampled ?? new AlwaysOnSampler();
this._localParentNotSampled =
config.localParentNotSampled ?? new AlwaysOffSampler();
}
shouldSample(context, traceId, spanName, spanKind, attributes, links) {
const parentContext = trace.getSpanContext(context);
if (!parentContext || !isSpanContextValid(parentContext)) {
return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.isRemote) {
if (parentContext.traceFlags & TraceFlags.SAMPLED) {
return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.traceFlags & TraceFlags.SAMPLED) {
return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
toString() {
return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
}
}
//# sourceMappingURL=ParentBasedSampler.js.map
{"version":3,"file":"ParentBasedSampler.js","sourceRoot":"","sources":["../../../src/sampler/ParentBasedSampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAGpD;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IACrB,KAAK,CAAU;IACf,oBAAoB,CAAU;IAC9B,uBAAuB,CAAU;IACjC,mBAAmB,CAAU;IAC7B,sBAAsB,CAAU;IAExC,YAAY,MAAgC;QAC1C,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC;QAEzB,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE;YACf,kBAAkB,CAChB,IAAI,KAAK,CAAC,wDAAwD,CAAC,CACpE,CAAC;YACF,IAAI,CAAC,KAAK,GAAG,IAAI,eAAe,EAAE,CAAC;SACpC;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ACN,CAAC;SACH;QAED,OAAO,IAAI,CAAC,sBAAsB,CAAC,YAAY,CAC7C,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,CACN,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,oBAAoB,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,yBAAyB,IAAI,CAAC,oBAAoB,CAAC,QAAQ,EAAE,4BAA4B,IAAI,CAAC,uBAAuB,CAAC,QAAQ,EAAE,wBAAwB,IAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE,2BAA2B,IAAI,CAAC,sBAAsB,CAAC,QAAQ,EAAE,GAAG,CAAC;IAClT,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
export declare class TraceIdRatioBasedSampler implements Sampler {
private readonly _ratio;
private _upperBound;
constructor(ratio?: number);
shouldSample(context: unknown, traceId: string): SamplingResult;
toString(): string;
private _normalize;
private _accumulate;
}
//# sourceMappingURL=TraceIdRatioBasedSampler.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { isValidTraceId } from '@opentelemetry/api';
import { SamplingDecision } from '../Sampler';
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
export class TraceIdRatioBasedSampler {
_ratio;
_upperBound;
constructor(ratio = 0) {
this._ratio = this._normalize(ratio);
this._upperBound = Math.floor(this._ratio * 0xffffffff);
}
shouldSample(context, traceId) {
return {
decision: isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound
? SamplingDecision.RECORD_AND_SAMPLED
: SamplingDecision.NOT_RECORD,
};
}
toString() {
return `TraceIdRatioBased{${this._ratio}}`;
}
_normalize(ratio) {
if (typeof ratio !== 'number' || isNaN(ratio))
return 0;
return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
}
_accumulate(traceId) {
let accumulation = 0;
for (let i = 0; i < 32; i += 8) {
let part = 0;
for (let j = 0; j < 8; j++) {
const c = traceId.charCodeAt(i + j);
// Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15
const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;
part = (part << 4) | v;
}
accumulation = (accumulation ^ part) >>> 0;
}
return accumulation;
}
}
//# sourceMappingURL=TraceIdRatioBasedSampler.js.map
{"version":3,"file":"TraceIdRatioBasedSampler.js","sourceRoot":"","sources":["../../../src/sampler/TraceIdRatioBasedSampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,2FAA2F;AAC3F,MAAM,OAAO,wBAAwB;IAClB,MAAM,CAAC;IAChB,WAAW,CAAS;IAE5B,YAAY,KAAK,GAAG,CAAC;QACnB,IAAI,CAAC,MAA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C,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;gBACrD,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;aACxB;YACD,YAAY,GAAG,CAAC,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;SAC5C;QACD,OAAO,YAAY,CAAC;IACtB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < 32; i += 8) {\n let part = 0;\n for (let j = 0; j < 8; j++) {\n const c = traceId.charCodeAt(i + j);\n // Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15\n const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;\n part = (part << 4) | v;\n }\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n"]}
/**
* Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const ATTR_OTEL_SPAN_PARENT_ORIGIN: "otel.span.parent.origin";
/**
* The result value of the sampler for this span
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const ATTR_OTEL_SPAN_SAMPLING_RESULT: "otel.span.sampling_result";
/**
* The number of created spans with `recording=true` for which the end operation has not been called yet.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const METRIC_OTEL_SDK_SPAN_LIVE: "otel.sdk.span.live";
/**
* The number of created spans.
*
* @note Implementations **MUST** record this metric for all spans, even for non-recording ones.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const METRIC_OTEL_SDK_SPAN_STARTED: "otel.sdk.span.started";
//# sourceMappingURL=semconv.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/*
* This file contains a copy of unstable semantic convention definitions
* used by this package.
* @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv
*/
/**
* Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin';
/**
* The result value of the sampler for this span
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export const ATTR_OTEL_SPAN_SAMPLING_RESULT = 'otel.span.sampling_result';
/**
* The number of created spans with `recording=true` for which the end operation has not been called yet.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live';
/**
* The number of created spans.
*
* @note Implementations **MUST** record this metric for all spans, even for non-recording ones.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started';
//# sourceMappingURL=semconv.js.map
{"version":3,"file":"semconv.js","sourceRoot":"","sources":["../../src/semconv.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,yBAAkC,CAAC;AAE/E;;;;GAIG;AACH,MAAM,CAAC,MAAM,8BAA8B,GACzC,2BAAoC,CAAC;AAEvC;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,oBAA6B,CAAC;AAEvE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,uBAAgC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n 'otel.span.sampling_result' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n"]}
import type { Context, Exception, HrTime, Link, Span as APISpan, SpanOptions as APISpanOptions, Attributes, AttributeValue, SpanContext, SpanKind, SpanStatus, TimeInput } from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { Resource } from '@opentelemetry/resources';
import type { ReadableSpan } from './export/ReadableSpan';
import type { SpanProcessor } from './SpanProcessor';
import type { TimedEvent } from './TimedEvent';
import type { SpanLimits } from './types';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
/**
* This type provides the properties of @link{ReadableSpan} at the same time
* of the Span API
*/
export type Span = APISpan & ReadableSpan;
type SpanOptions = Omit<APISpanOptions, 'root'> & {
resource: Resource;
scope: InstrumentationScope;
context: Context;
spanContext: SpanContext;
name: string;
kind: SpanKind;
parentSpanContext?: SpanContext;
spanLimits: SpanLimits;
spanProcessor: SpanProcessor;
recordEndMetrics?: () => void;
};
/**
* This class represents a span.
*/
export declare class SpanImpl implements Span {
private readonly _spanContext;
readonly kind: SpanKind;
readonly parentSpanContext?: SpanContext;
readonly attributes: Attributes;
readonly links: Link[];
readonly events: TimedEvent[];
readonly startTime: HrTime;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
private _droppedAttributesCount;
private _droppedEventsCount;
private _droppedLinksCount;
private _attributesCount;
name: string;
status: SpanStatus;
endTime: HrTime;
private _ended;
private _duration;
private readonly _spanProcessor;
private readonly _spanLimits;
private readonly _attributeValueLengthLimit;
private readonly _recordEndMetrics?;
private readonly _performanceStartTime;
private readonly _performanceOffset;
private readonly _startTimeProvided;
/**
* Constructs a new SpanImpl instance.
*/
constructor(opts: SpanOptions);
spanContext(): SpanContext;
setAttribute(key: string, value?: AttributeValue): this;
setAttributes(attributes: Attributes): this;
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name: string, attributesOrStartTime?: Attributes | TimeInput, timeStamp?: TimeInput): this;
addLink(link: Link): this;
addLinks(links: Link[]): this;
setStatus(status: SpanStatus): this;
updateName(name: string): this;
end(endTime?: TimeInput): void;
private _getTime;
isRecording(): boolean;
recordException(exception: Exception, time?: TimeInput): void;
get duration(): HrTime;
get ended(): boolean;
get droppedAttributesCount(): number;
get droppedEventsCount(): number;
get droppedLinksCount(): number;
private _isSpanEnded;
private _truncateToLimitUtil;
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
private _truncateToSize;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
export {};
//# sourceMappingURL=Span.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { diag, SpanStatusCode } from '@opentelemetry/api';
import { addHrTimes, millisToHrTime, hrTime, hrTimeDuration, isAttributeValue, isTimeInput, isTimeInputHrTime, otperformance, sanitizeAttributes, } from '@opentelemetry/core';
import { ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, } from '@opentelemetry/semantic-conventions';
import { ExceptionEventName } from './enums';
import { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';
/**
* This class represents a span.
*/
export class SpanImpl {
// Below properties are included to implement ReadableSpan for export
// purposes but are not intended to be written-to directly.
_spanContext;
kind;
parentSpanContext;
attributes = {};
links = [];
events = [];
startTime;
resource;
instrumentationScope;
_droppedAttributesCount = 0;
_droppedEventsCount = 0;
_droppedLinksCount = 0;
_attributesCount = 0;
name;
status = {
code: SpanStatusCode.UNSET,
};
endTime = [0, 0];
_ended = false;
_duration = [-1, -1];
_spanProcessor;
_spanLimits;
_attributeValueLengthLimit;
_recordEndMetrics;
_performanceStartTime;
_performanceOffset;
_startTimeProvided;
/**
* Constructs a new SpanImpl instance.
*/
constructor(opts) {
const now = Date.now();
this._spanContext = opts.spanContext;
this._performanceStartTime = otperformance.now();
this._performanceOffset =
now - (this._performanceStartTime + otperformance.timeOrigin);
this._startTimeProvided = opts.startTime != null;
this._spanLimits = opts.spanLimits;
this._attributeValueLengthLimit =
this._spanLimits.attributeValueLengthLimit ?? 0;
this._spanProcessor = opts.spanProcessor;
this.name = opts.name;
this.parentSpanContext = opts.parentSpanContext;
this.kind = opts.kind;
if (opts.links) {
for (const link of opts.links) {
this.addLink(link);
}
}
this.startTime = this._getTime(opts.startTime ?? now);
this.resource = opts.resource;
this.instrumentationScope = opts.scope;
this._recordEndMetrics = opts.recordEndMetrics;
if (opts.attributes != null) {
this.setAttributes(opts.attributes);
}
this._spanProcessor.onStart(this, opts.context);
}
spanContext() {
return this._spanContext;
}
setAttribute(key, value) {
if (value == null || this._isSpanEnded())
return this;
if (key.length === 0) {
diag.warn(`Invalid attribute key: ${key}`);
return this;
}
if (!isAttributeValue(value)) {
diag.warn(`Invalid attribute value set for key: ${key}`);
return this;
}
const { attributeCountLimit } = this._spanLimits;
const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
if (attributeCountLimit !== undefined &&
this._attributesCount >= attributeCountLimit &&
isNewKey) {
this._droppedAttributesCount++;
return this;
}
this.attributes[key] = this._truncateToSize(value);
if (isNewKey) {
this._attributesCount++;
}
return this;
}
setAttributes(attributes) {
for (const key in attributes) {
if (Object.prototype.hasOwnProperty.call(attributes, key)) {
this.setAttribute(key, attributes[key]);
}
}
return this;
}
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name, attributesOrStartTime, timeStamp) {
if (this._isSpanEnded())
return this;
const { eventCountLimit } = this._spanLimits;
if (eventCountLimit === 0) {
diag.warn('No events allowed.');
this._droppedEventsCount++;
return this;
}
if (eventCountLimit !== undefined &&
this.events.length >= eventCountLimit) {
if (this._droppedEventsCount === 0) {
diag.debug('Dropping extra events.');
}
this.events.shift();
this._droppedEventsCount++;
}
if (isTimeInput(attributesOrStartTime)) {
if (!isTimeInput(timeStamp)) {
timeStamp = attributesOrStartTime;
}
attributesOrStartTime = undefined;
}
const sanitized = sanitizeAttributes(attributesOrStartTime);
const { attributePerEventCountLimit } = this._spanLimits;
const attributes = {};
let droppedAttributesCount = 0;
let eventAttributesCount = 0;
for (const attr in sanitized) {
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
continue;
}
const attrVal = sanitized[attr];
if (attributePerEventCountLimit !== undefined &&
eventAttributesCount >= attributePerEventCountLimit) {
droppedAttributesCount++;
continue;
}
attributes[attr] = this._truncateToSize(attrVal);
eventAttributesCount++;
}
this.events.push({
name,
attributes,
time: this._getTime(timeStamp),
droppedAttributesCount,
});
return this;
}
addLink(link) {
if (this._isSpanEnded())
return this;
const { linkCountLimit } = this._spanLimits;
if (linkCountLimit === 0) {
this._droppedLinksCount++;
return this;
}
if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {
if (this._droppedLinksCount === 0) {
diag.debug('Dropping extra links.');
}
this.links.shift();
this._droppedLinksCount++;
}
const { attributePerLinkCountLimit } = this._spanLimits;
const sanitized = sanitizeAttributes(link.attributes);
const attributes = {};
let droppedAttributesCount = 0;
let linkAttributesCount = 0;
for (const attr in sanitized) {
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
continue;
}
const attrVal = sanitized[attr];
if (attributePerLinkCountLimit !== undefined &&
linkAttributesCount >= attributePerLinkCountLimit) {
droppedAttributesCount++;
continue;
}
attributes[attr] = this._truncateToSize(attrVal);
linkAttributesCount++;
}
const processedLink = { context: link.context };
if (linkAttributesCount > 0) {
processedLink.attributes = attributes;
}
if (droppedAttributesCount > 0) {
processedLink.droppedAttributesCount = droppedAttributesCount;
}
this.links.push(processedLink);
return this;
}
addLinks(links) {
for (const link of links) {
this.addLink(link);
}
return this;
}
setStatus(status) {
if (this._isSpanEnded())
return this;
if (status.code === SpanStatusCode.UNSET)
return this;
if (this.status.code === SpanStatusCode.OK)
return this;
const newStatus = { code: status.code };
// When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`,
// TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()
// as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or
// undefined to avoid an incorrect type causing issues downstream.
if (status.code === SpanStatusCode.ERROR) {
if (typeof status.message === 'string') {
newStatus.message = status.message;
}
else if (status.message != null) {
diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
}
}
this.status = newStatus;
return this;
}
updateName(name) {
if (this._isSpanEnded())
return this;
this.name = name;
return this;
}
end(endTime) {
if (this._isSpanEnded()) {
diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
return;
}
this.endTime = this._getTime(endTime);
this._duration = hrTimeDuration(this.startTime, this.endTime);
if (this._duration[0] < 0) {
diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime);
this.endTime = this.startTime.slice();
this._duration = [0, 0];
}
if (this._droppedEventsCount > 0) {
diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
}
if (this._droppedLinksCount > 0) {
diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);
}
if (this._spanProcessor.onEnding) {
this._spanProcessor.onEnding(this);
}
this._recordEndMetrics?.();
this._ended = true;
this._spanProcessor.onEnd(this);
}
_getTime(inp) {
if (typeof inp === 'number' && inp <= otperformance.now()) {
// must be a performance timestamp
// apply correction and convert to hrtime
return hrTime(inp + this._performanceOffset);
}
if (typeof inp === 'number') {
return millisToHrTime(inp);
}
if (inp instanceof Date) {
return millisToHrTime(inp.getTime());
}
if (isTimeInputHrTime(inp)) {
return inp;
}
if (this._startTimeProvided) {
// if user provided a time for the start manually
// we can't use duration to calculate event/end times
return millisToHrTime(Date.now());
}
const msDuration = otperformance.now() - this._performanceStartTime;
return addHrTimes(this.startTime, millisToHrTime(msDuration));
}
isRecording() {
return this._ended === false;
}
recordException(exception, time) {
const attributes = {};
if (typeof exception === 'string') {
attributes[ATTR_EXCEPTION_MESSAGE] = exception;
}
else if (exception) {
if (exception.code) {
attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();
}
else if (exception.name) {
attributes[ATTR_EXCEPTION_TYPE] = exception.name;
}
if (exception.message) {
attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;
}
if (exception.stack) {
attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;
}
}
// these are minimum requirements from spec
if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {
this.addEvent(ExceptionEventName, attributes, time);
}
else {
diag.warn(`Failed to record an exception ${exception}`);
}
}
get duration() {
return this._duration;
}
get ended() {
return this._ended;
}
get droppedAttributesCount() {
return this._droppedAttributesCount;
}
get droppedEventsCount() {
return this._droppedEventsCount;
}
get droppedLinksCount() {
return this._droppedLinksCount;
}
_isSpanEnded() {
if (this._ended) {
const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
}
return this._ended;
}
// Utility function to truncate given value within size
// for value type of string, will truncate to given limit
// for type of non-string, will return same value
_truncateToLimitUtil(value, limit) {
if (value.length <= limit) {
return value;
}
return value.substring(0, limit);
}
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
_truncateToSize(value) {
const limit = this._attributeValueLengthLimit;
// Check limit
if (limit <= 0) {
// Negative values are invalid, so do not truncate
diag.warn(`Attribute value limit must be positive, got ${limit}`);
return value;
}
// String
if (typeof value === 'string') {
return this._truncateToLimitUtil(value, limit);
}
// Array of strings
if (Array.isArray(value)) {
return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val);
}
// Other types, no need to apply value length limit
return value;
}
[inspectCustom](depth, options, inspect) {
const payload = {
name: this.name,
kind: this.kind,
spanContext: this._spanContext,
parentSpanContext: this.parentSpanContext,
status: this.status,
startTime: this.startTime,
endTime: this.endTime,
duration: this._duration,
ended: this._ended,
attributes: this.attributes,
events: this.events,
links: this.links,
droppedAttributesCount: this._droppedAttributesCount,
droppedEventsCount: this._droppedEventsCount,
droppedLinksCount: this._droppedLinksCount,
instrumentationScope: this.instrumentationScope,
resource: { attributes: settledResourceAttributes(this.resource) },
};
return formatInspect('SpanImpl', payload, depth, options, inspect);
}
}
//# sourceMappingURL=Span.js.map
{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAgBH,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAE1D,OAAO,EACL,UAAU,EACV,cAAc,EACd,MAAM,EACN,cAAc,EACd,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EACjB,aAAa,EACb,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EAAE,kBAAkB,EAAE,MA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C,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CACtE,CAAC;SACH;QAED,mDAAmD;QACnD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,CAAC,aAAa,CAAC,CACb,KAAa,EACb,OAA0C,EAC1C,OAA8B;QAE9B,MAAM,OAAO,GAAG;YACd,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,YAAY;YAC9B,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,KAAK,EAAE,IAAI,CAAC,MAAM;YAClB,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,sBAAsB,EAAE,IAAI,CAAC,uBAAuB;YACpD,kBAAkB,EAAE,IAAI,CAAC,mBAAmB;YAC5C,iBAAiB,EAAE,IAAI,CAAC,kBAAkB;YAC1C,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,QAAQ,EAAE,EAAE,UAAU,EAAE,yBAAyB,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;SACnE,CAAC;QACF,OAAO,aAAa,CAAC,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanOptions as APISpanOptions,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n // Required here to override optional `kind` from the API's SpanOptions\n // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n private readonly _recordEndMetrics?: () => void;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit ?? 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n eventAttributesCount++;\n }\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n\n addLink(link: Link): this {\n if (this._isSpanEnded()) return this;\n\n const { linkCountLimit } = this._spanLimits;\n\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n linkAttributesCount++;\n }\n\n const processedLink: Link = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n\n this.links.push(processedLink);\n return this;\n }\n\n addLinks(links: Link[]): this {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n if (status.code === SpanStatusCode.UNSET) return this;\n if (this.status.code === SpanStatusCode.OK) return this;\n\n const newStatus: SpanStatus = { code: status.code };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n } else if (status.message != null) {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n }\n }\n\n this.status = newStatus;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(\n `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const payload = {\n name: this.name,\n kind: this.kind,\n spanContext: this._spanContext,\n parentSpanContext: this.parentSpanContext,\n status: this.status,\n startTime: this.startTime,\n endTime: this.endTime,\n duration: this._duration,\n ended: this._ended,\n attributes: this.attributes,\n events: this.events,\n links: this.links,\n droppedAttributesCount: this._droppedAttributesCount,\n droppedEventsCount: this._droppedEventsCount,\n droppedLinksCount: this._droppedLinksCount,\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this.resource) },\n };\n return formatInspect('SpanImpl', payload, depth, options, inspect);\n }\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './export/ReadableSpan';
import type { Span } from './Span';
/**
* SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks
* for when a {@link Span} is started or when a {@link Span} is ended.
*/
export interface SpanProcessor {
/**
* Forces to export all finished spans
*/
forceFlush(): Promise<void>;
/**
* Called when a {@link Span} is started, if the `span.isRecording()`
* returns true.
* @param span the Span that just started.
*/
onStart(span: Span, parentContext: Context): void;
/**
* Called when a {@link Span} is ending, if the `span.isRecording()`
* returns true.
* @param span the Span that is ending.
*
* @experimental This method is experimental and may break in minor versions of this package
*/
onEnding?(span: Span): void;
/**
* Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`
* returns true.
* @param span the Span that just ended.
*/
onEnd(span: ReadableSpan): void;
/**
* Shuts down the processor. Called when SDK is shut down. This is an
* opportunity for processor to do any cleanup required.
*/
shutdown(): Promise<void>;
}
//# sourceMappingURL=SpanProcessor.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=SpanProcessor.js.map
{"version":3,"file":"SpanProcessor.js","sourceRoot":"","sources":["../../src/SpanProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\n\n/**\n * SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks\n * for when a {@link Span} is started or when a {@link Span} is ended.\n */\nexport interface SpanProcessor {\n /**\n * Forces to export all finished spans\n */\n forceFlush(): Promise<void>;\n\n /**\n * Called when a {@link Span} is started, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just started.\n */\n onStart(span: Span, parentContext: Context): void;\n\n /**\n * Called when a {@link Span} is ending, if the `span.isRecording()`\n * returns true.\n * @param span the Span that is ending.\n *\n * @experimental This method is experimental and may break in minor versions of this package\n */\n onEnding?(span: Span): void;\n\n /**\n * Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just ended.\n */\n onEnd(span: ReadableSpan): void;\n\n /**\n * Shuts down the processor. Called when SDK is shut down. This is an\n * opportunity for processor to do any cleanup required.\n */\n shutdown(): Promise<void>;\n}\n"]}
import type { HrTime, Attributes } from '@opentelemetry/api';
/**
* Represents a timed event.
* A timed event is an event with a timestamp.
*/
export interface TimedEvent {
time: HrTime;
/** The name of the event. */
name: string;
/** The attributes of the event. */
attributes?: Attributes;
/** Count of attributes of the event that were dropped due to collection limits */
droppedAttributesCount?: number;
}
//# sourceMappingURL=TimedEvent.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=TimedEvent.js.map
{"version":3,"file":"TimedEvent.js","sourceRoot":"","sources":["../../src/TimedEvent.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime, Attributes } from '@opentelemetry/api';\n\n/**\n * Represents a timed event.\n * A timed event is an event with a timestamp.\n */\nexport interface TimedEvent {\n time: HrTime;\n /** The name of the event. */\n name: string;\n /** The attributes of the event. */\n attributes?: Attributes;\n /** Count of attributes of the event that were dropped due to collection limits */\n droppedAttributesCount?: number;\n}\n"]}
import * as api from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { GeneralLimits, SpanLimits, TracerConfig } from './types';
import type { SpanProcessor } from './SpanProcessor';
import type { Resource } from '@opentelemetry/resources';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
/**
* This class represents a basic tracer.
*/
export declare class Tracer implements api.Tracer {
private readonly _sampler;
private readonly _generalLimits;
private readonly _spanLimits;
private readonly _idGenerator;
readonly instrumentationScope: InstrumentationScope;
private readonly _resource;
private readonly _spanProcessor;
private readonly _tracerMetrics;
/**
* Constructs a new Tracer instance.
*/
constructor(instrumentationScope: InstrumentationScope, config: TracerConfig, resource: Resource, spanProcessor: SpanProcessor);
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
startSpan(name: string, options?: api.SpanOptions, context?: api.Context): api.Span;
/**
* Starts a new {@link Span} and calls the given function passing it the
* created span as first argument.
* Additionally the new span gets set in context and this context is activated
* for the duration of the function call.
*
* **Important**: The callback function is responsible for calling `span.end()`
* to finish the span. Unlike some other OpenTelemetry implementations, the span
* is NOT automatically ended when the callback returns. If `span.end()` is not
* called, the span will never be exported and will be silently lost.
*
* @param name The name of the span
* @param [options] SpanOptions used for span creation
* @param [context] Context to use to extract parent
* @param fn function called in the context of the span and receives the newly created span as an argument
* @returns return value of fn
* @example
* const something = tracer.startActiveSpan('op', span => {
* try {
* do some work
* span.setStatus({code: SpanStatusCode.OK});
* return something;
* } catch (err) {
* span.setStatus({
* code: SpanStatusCode.ERROR,
* message: err.message,
* });
* throw err;
* } finally {
* span.end();
* }
* });
* @example
* const span = tracer.startActiveSpan('op', span => {
* try {
* do some work
* return span;
* } catch (err) {
* span.setStatus({
* code: SpanStatusCode.ERROR,
* message: err.message,
* });
* throw err;
* }
* });
* do some more work
* span.end();
*/
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, fn: F): ReturnType<F>;
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, opts: api.SpanOptions, fn: F): ReturnType<F>;
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, opts: api.SpanOptions, ctx: api.Context, fn: F): ReturnType<F>;
/** Returns the active {@link GeneralLimits}. */
getGeneralLimits(): GeneralLimits;
/** Returns the active {@link SpanLimits}. */
getSpanLimits(): SpanLimits;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
//# sourceMappingURL=Tracer.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import * as api from '@opentelemetry/api';
import { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';
import { SpanImpl } from './Span';
import { mergeConfig } from './utility';
import { RandomIdGenerator } from './platform';
import { TracerMetrics } from './TracerMetrics';
import { VERSION } from './version';
import { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';
/**
* This class represents a basic tracer.
*/
export class Tracer {
_sampler;
_generalLimits;
_spanLimits;
_idGenerator;
instrumentationScope;
_resource;
_spanProcessor;
_tracerMetrics;
/**
* Constructs a new Tracer instance.
*/
constructor(instrumentationScope, config, resource, spanProcessor) {
const localConfig = mergeConfig(config);
this._sampler = localConfig.sampler;
this._generalLimits = localConfig.generalLimits;
this._spanLimits = localConfig.spanLimits;
this._idGenerator = config.idGenerator || new RandomIdGenerator();
this._resource = resource;
this._spanProcessor = spanProcessor;
this.instrumentationScope = instrumentationScope;
const meter = localConfig.meterProvider
? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)
: api.createNoopMeter();
this._tracerMetrics = new TracerMetrics(meter);
}
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
startSpan(name, options = {}, context = api.context.active()) {
// remove span from context in case a root span is requested via options
if (options.root) {
context = api.trace.deleteSpan(context);
}
const parentSpan = api.trace.getSpan(context);
if (isTracingSuppressed(context)) {
api.diag.debug('Instrumentation suppressed, returning Noop Span');
const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);
return nonRecordingSpan;
}
const parentSpanContext = parentSpan?.spanContext();
const spanId = this._idGenerator.generateSpanId();
let validParentSpanContext;
let traceId;
let traceState;
if (!parentSpanContext ||
!api.trace.isSpanContextValid(parentSpanContext)) {
// New root span.
traceId = this._idGenerator.generateTraceId();
}
else {
// New child span.
traceId = parentSpanContext.traceId;
traceState = parentSpanContext.traceState;
validParentSpanContext = parentSpanContext;
}
const spanKind = options.kind ?? api.SpanKind.INTERNAL;
const links = (options.links ?? []).map(link => {
return {
context: link.context,
attributes: sanitizeAttributes(link.attributes),
};
});
const attributes = sanitizeAttributes(options.attributes);
// make sampling decision
const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links);
const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision);
traceState = samplingResult.traceState ?? traceState;
const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED
? api.TraceFlags.SAMPLED
: api.TraceFlags.NONE;
const spanContext = { traceId, spanId, traceFlags, traceState };
if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {
api.diag.debug('Recording is off, propagating context in a non-recording span');
const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);
return nonRecordingSpan;
}
// Set initial span attributes. The attributes object may have been mutated
// by the sampler, so we sanitize the merged attributes before setting them.
const initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes));
const span = new SpanImpl({
resource: this._resource,
scope: this.instrumentationScope,
context,
spanContext,
name,
kind: spanKind,
links,
parentSpanContext: validParentSpanContext,
attributes: initAttributes,
startTime: options.startTime,
spanProcessor: this._spanProcessor,
spanLimits: this._spanLimits,
recordEndMetrics,
});
return span;
}
startActiveSpan(name, arg2, arg3, arg4) {
let opts;
let ctx;
let fn;
if (arguments.length < 2) {
return;
}
else if (arguments.length === 2) {
fn = arg2;
}
else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
}
else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
const parentContext = ctx ?? api.context.active();
const span = this.startSpan(name, opts, parentContext);
const contextWithSpanSet = api.trace.setSpan(parentContext, span);
return api.context.with(contextWithSpanSet, fn, undefined, span);
}
/** Returns the active {@link GeneralLimits}. */
getGeneralLimits() {
return this._generalLimits;
}
/** Returns the active {@link SpanLimits}. */
getSpanLimits() {
return this._spanLimits;
}
[inspectCustom](depth, options, inspect) {
const payload = {
instrumentationScope: this.instrumentationScope,
resource: { attributes: settledResourceAttributes(this._resource) },
spanLimits: this._spanLimits,
generalLimits: this._generalLimits,
};
return formatInspect('Tracer', payload, depth, options, inspect);
}
}
//# sourceMappingURL=Tracer.js.map
{"version":3,"file":"Tracer.js","sourceRoot":"","sources":["../../src/Tracer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAIxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EACL,aAAa,EACb,aAAa,EACb,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AAEnB;;GAEG;AACH,MAAM,OAA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EAAE,IAAI,CAAC,oBAAoB;YAC/C,QAAQ,EAAE,EAAE,UAAU,EAAE,yBAAyB,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;YACnE,UAAU,EAAE,IAAI,CAAC,WAAW;YAC5B,aAAa,EAAE,IAAI,CAAC,cAAc;SACnC,CAAC;QACF,OAAO,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACnE,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n private readonly _tracerMetrics: TracerMetrics;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n\n const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\n this._tracerMetrics = new TracerMetrics(meter);\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n const recordEndMetrics = this._tracerMetrics.startSpan(\n parentSpanContext,\n samplingResult.decision\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n recordEndMetrics,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * **Important**: The callback function is responsible for calling `span.end()`\n * to finish the span. Unlike some other OpenTelemetry implementations, the span\n * is NOT automatically ended when the callback returns. If `span.end()` is not\n * called, the span will never be exported and will be silently lost.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const payload = {\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this._resource) },\n spanLimits: this._spanLimits,\n generalLimits: this._generalLimits,\n };\n return formatInspect('Tracer', payload, depth, options, inspect);\n }\n}\n"]}
import type { Meter, SpanContext } from '@opentelemetry/api';
import { SamplingDecision } from './Sampler';
/**
* Generates `otel.sdk.span.*` metrics.
* https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
*/
export declare class TracerMetrics {
private readonly startedSpans;
private readonly liveSpans;
constructor(meter: Meter);
startSpan(parentSpanCtx: SpanContext | undefined, samplingDecision: SamplingDecision): () => void;
}
//# sourceMappingURL=TracerMetrics.d.ts.map
import { SamplingDecision } from './Sampler';
import { ATTR_OTEL_SPAN_PARENT_ORIGIN, ATTR_OTEL_SPAN_SAMPLING_RESULT, METRIC_OTEL_SDK_SPAN_LIVE, METRIC_OTEL_SDK_SPAN_STARTED, } from './semconv';
/**
* Generates `otel.sdk.span.*` metrics.
* https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
*/
export class TracerMetrics {
startedSpans;
liveSpans;
constructor(meter) {
this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {
unit: '{span}',
description: 'The number of created spans.',
});
this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {
unit: '{span}',
description: 'The number of currently live spans.',
});
}
startSpan(parentSpanCtx, samplingDecision) {
const samplingDecisionStr = samplingDecisionToString(samplingDecision);
this.startedSpans.add(1, {
[ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),
[ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,
});
if (samplingDecision === SamplingDecision.NOT_RECORD) {
return () => { };
}
const liveSpanAttributes = {
[ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,
};
this.liveSpans.add(1, liveSpanAttributes);
return () => {
this.liveSpans.add(-1, liveSpanAttributes);
};
}
}
function parentOrigin(parentSpanContext) {
if (!parentSpanContext) {
return 'none';
}
if (parentSpanContext.isRemote) {
return 'remote';
}
return 'local';
}
function samplingDecisionToString(decision) {
switch (decision) {
case SamplingDecision.RECORD_AND_SAMPLED:
return 'RECORD_AND_SAMPLE';
case SamplingDecision.RECORD:
return 'RECORD_ONLY';
case SamplingDecision.NOT_RECORD:
return 'DROP';
}
}
//# sourceMappingURL=TracerMetrics.js.map
{"version":3,"file":"TracerMetrics.js","sourceRoot":"","sources":["../../src/TracerMetrics.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,gBAAgB,EAA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B,OAAO,MAAM,CAAC;KACf;IACD,IAAI,iBAAiB,CAAC,QAAQ,EAAE;QAC9B,OAAO,QAAQ,CAAC;KACjB;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,wBAAwB,CAAC,QAA0B;IAC1D,QAAQ,QAAQ,EAAE;QAChB,KAAK,gBAAgB,CAAC,kBAAkB;YACtC,OAAO,mBAAmB,CAAC;QAC7B,KAAK,gBAAgB,CAAC,MAAM;YAC1B,OAAO,aAAa,CAAC;QACvB,KAAK,gBAAgB,CAAC,UAAU;YAC9B,OAAO,MAAM,CAAC;KACjB;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Counter,\n Meter,\n SpanContext,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n ATTR_OTEL_SPAN_PARENT_ORIGIN,\n ATTR_OTEL_SPAN_SAMPLING_RESULT,\n METRIC_OTEL_SDK_SPAN_LIVE,\n METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n private readonly startedSpans: Counter;\n private readonly liveSpans: UpDownCounter;\n\n constructor(meter: Meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n\n startSpan(\n parentSpanCtx: SpanContext | undefined,\n samplingDecision: SamplingDecision\n ): () => void {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => {};\n }\n\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n"]}
import type { ContextManager, MeterProvider, TextMapPropagator } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
import type { IdGenerator } from './IdGenerator';
import type { Sampler } from './Sampler';
import type { SpanProcessor } from './SpanProcessor';
/**
* TracerConfig provides an interface for configuring a Basic Tracer.
*/
export interface TracerConfig {
/**
* Sampler determines if a span should be recorded or should be a NoopSpan.
*/
sampler?: Sampler;
/** General Limits */
generalLimits?: GeneralLimits;
/** Span Limits */
spanLimits?: SpanLimits;
/** Resource associated with trace telemetry */
resource?: Resource;
/**
* Generator of trace and span IDs
* The default idGenerator generates random ids
*/
idGenerator?: IdGenerator;
/**
* How long the forceFlush can run before it is cancelled.
* The default value is 30000ms
*/
forceFlushTimeoutMillis?: number;
/**
* List of SpanProcessor for the tracer
*/
spanProcessors?: SpanProcessor[];
/**
* A meter provider to record trace SDK metrics to.
* @experimental This option is experimental and is subject to breaking changes in minor releases.
*/
meterProvider?: MeterProvider;
}
/**
* Configuration options for registering the API with the SDK.
* Undefined values may be substituted for defaults, and null
* values will not be registered.
*/
export interface SDKRegistrationConfig {
/** Propagator to register as the global propagator */
propagator?: TextMapPropagator | null;
/** Context manager to register as the global context manager */
contextManager?: ContextManager | null;
}
/** Global configuration limits of trace service */
export interface GeneralLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per trace */
attributeCountLimit?: number;
}
/** Global configuration of trace service */
export interface SpanLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per span */
attributeCountLimit?: number;
/** linkCountLimit is number of links per span */
linkCountLimit?: number;
/** eventCountLimit is number of message events per span */
eventCountLimit?: number;
/** attributePerEventCountLimit is the maximum number of attributes allowed per span event */
attributePerEventCountLimit?: number;
/** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */
attributePerLinkCountLimit?: number;
}
/** Interface configuration for a buffer. */
export interface BufferConfig {
/** The maximum batch size of every export. It must be smaller or equal to
* maxQueueSize. The default value is 512. */
maxExportBatchSize?: number;
/** The delay interval in milliseconds between two consecutive exports.
* The default value is 5000ms. */
scheduledDelayMillis?: number;
/** How long the export can run before it is cancelled.
* The default value is 30000ms */
exportTimeoutMillis?: number;
/** The maximum queue size. After the size is reached spans are dropped.
* The default value is 2048. */
maxQueueSize?: number;
}
/** Interface configuration for BatchSpanProcessor on browser */
export interface BatchSpanProcessorBrowserConfig extends BufferConfig {
/** Disable flush when a user navigates to a new page, closes the tab or the browser, or,
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}
//# sourceMappingURL=types.d.ts.map
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=types.js.map
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n ContextManager,\n MeterProvider,\n TextMapPropagator,\n} from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { IdGenerator } from './IdGenerator';\nimport type { Sampler } from './Sampler';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * TracerConfig provides an interface for configuring a Basic Tracer.\n */\nexport interface TracerConfig {\n /**\n * Sampler determines if a span should be recorded or should be a NoopSpan.\n */\n sampler?: Sampler;\n\n /** General Limits */\n generalLimits?: GeneralLimits;\n\n /** Span Limits */\n spanLimits?: SpanLimits;\n\n /** Resource associated with trace telemetry */\n resource?: Resource;\n\n /**\n * Generator of trace and span IDs\n * The default idGenerator generates random ids\n */\n idGenerator?: IdGenerator;\n\n /**\n * How long the forceFlush can run before it is cancelled.\n * The default value is 30000ms\n */\n forceFlushTimeoutMillis?: number;\n\n /**\n * List of SpanProcessor for the tracer\n */\n spanProcessors?: SpanProcessor[];\n\n /**\n * A meter provider to record trace SDK metrics to.\n * @experimental This option is experimental and is subject to breaking changes in minor releases.\n */\n meterProvider?: MeterProvider;\n}\n\n/**\n * Configuration options for registering the API with the SDK.\n * Undefined values may be substituted for defaults, and null\n * values will not be registered.\n */\nexport interface SDKRegistrationConfig {\n /** Propagator to register as the global propagator */\n propagator?: TextMapPropagator | null;\n\n /** Context manager to register as the global context manager */\n contextManager?: ContextManager | null;\n}\n\n/** Global configuration limits of trace service */\nexport interface GeneralLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per trace */\n attributeCountLimit?: number;\n}\n\n/** Global configuration of trace service */\nexport interface SpanLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per span */\n attributeCountLimit?: number;\n /** linkCountLimit is number of links per span */\n linkCountLimit?: number;\n /** eventCountLimit is number of message events per span */\n eventCountLimit?: number;\n /** attributePerEventCountLimit is the maximum number of attributes allowed per span event */\n attributePerEventCountLimit?: number;\n /** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */\n attributePerLinkCountLimit?: number;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached spans are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\n/** Interface configuration for BatchSpanProcessor on browser */\nexport interface BatchSpanProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n"]}
import type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';
import type { TracerConfig } from './types';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
export declare enum ForceFlushState {
'resolved' = 0,
'timeout' = 1,
'error' = 2,
'unresolved' = 3
}
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
export declare class BasicTracerProvider implements TracerProvider {
private readonly _config;
private readonly _tracers;
private readonly _resource;
private readonly _activeSpanProcessor;
constructor(config?: TracerConfig);
getTracer(name: string, version?: string, options?: {
schemaUrl?: string;
}): ApiTracer;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
//# sourceMappingURL=BasicTracerProvider.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasicTracerProvider = exports.ForceFlushState = void 0;
const core_1 = require("@opentelemetry/core");
const resources_1 = require("@opentelemetry/resources");
const Tracer_1 = require("./Tracer");
const config_1 = require("./config");
const MultiSpanProcessor_1 = require("./MultiSpanProcessor");
const utility_1 = require("./utility");
const inspect_1 = require("./inspect");
var ForceFlushState;
(function (ForceFlushState) {
ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
ForceFlushState[ForceFlushState["error"] = 2] = "error";
ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
})(ForceFlushState = exports.ForceFlushState || (exports.ForceFlushState = {}));
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
class BasicTracerProvider {
_config;
_tracers = new Map();
_resource;
_activeSpanProcessor;
constructor(config = {}) {
const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config));
this._resource = mergedConfig.resource ?? (0, resources_1.defaultResource)();
this._config = Object.assign({}, mergedConfig, {
resource: this._resource,
});
const spanProcessors = [];
if (config.spanProcessors?.length) {
spanProcessors.push(...config.spanProcessors);
}
this._activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(spanProcessors);
}
getTracer(name, version, options) {
const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;
if (!this._tracers.has(key)) {
this._tracers.set(key, new Tracer_1.Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));
}
return this._tracers.get(key);
}
forceFlush() {
const timeout = this._config.forceFlushTimeoutMillis;
const promises = this._activeSpanProcessor['_spanProcessors'].map((spanProcessor) => {
return new Promise(resolve => {
let state;
const timeoutInterval = setTimeout(() => {
resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
state = ForceFlushState.timeout;
}, timeout);
spanProcessor
.forceFlush()
.then(() => {
clearTimeout(timeoutInterval);
if (state !== ForceFlushState.timeout) {
state = ForceFlushState.resolved;
resolve(state);
}
})
.catch(error => {
clearTimeout(timeoutInterval);
state = ForceFlushState.error;
resolve(error);
});
});
});
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(results => {
const errors = results.filter(result => result !== ForceFlushState.resolved);
if (errors.length > 0) {
reject(errors);
}
else {
resolve();
}
})
.catch(error => reject([error]));
});
}
shutdown() {
return this._activeSpanProcessor.shutdown();
}
[inspect_1.inspectCustom](depth, options, inspect) {
const processors = this._activeSpanProcessor['_spanProcessors'];
const payload = {
resource: { attributes: (0, inspect_1.settledResourceAttributes)(this._resource) },
tracers: Array.from(this._tracers.keys()),
spanProcessors: processors.map(p => p.constructor?.name ?? 'SpanProcessor'),
};
return (0, inspect_1.formatInspect)('BasicTracerProvider', payload, depth, options, inspect);
}
}
exports.BasicTracerProvider = BasicTracerProvider;
//# sourceMappingURL=BasicTracerProvider.js.map
{"version":3,"file":"BasicTracerProvider.js","sourceRoot":"","sources":["../../src/BasicTracerProvider.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,8CAA4C;AAE5C,wDAA2D;AAE3D,qCAAkC;AAClC,qCAA6C;AAC7C,6DAA0D;AAE1D,uCAA8C;AAE9C,uCAImB;AAEnB,IAAY,eAKX;AALD,WAAY,eAAe;IACzB,6DAAU,CAAA;IACV,2DAAS,CAAA;IACT,uDAAO,CAAA;IACP,iEAAY,CAAA;AACd,CAAC,EALW,eAAe,GAAf,uBAAe,KAAf,uBAAe,QAK1B;AAED;;GAEG;AACH,MAAa,mBAAmB;IACb,OAAO,CAAe;IACtB,QAAQ,GAAwB,IAAI,GAAG,EAAE,CAAC;IAC1C,SAAS,CAAW;IACpB,oBAAoB,CAAqB;IAE1D,YAAY,SAAuB,EAAE;QACnC,MAAM,YAAY,GAAG,IAAA,YAAK,EACxB,EAAE,EACF,IAAA,0BAAiB,GAAE,EACnB,IAAA,2BAAiB,EAAC,MAAM,CAAC,CAC1B,CAAC;QACF,IAAI,CAAC,SAAS,GAAG,YAAY,CAAC,QAAQ,IAAI,IAAA,2BAAe,GAAE,CAAC;QAE5D,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,EAAE;YAC7C,QAAQ,EAAE,IAAI,CAAC,SA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CAAC,oBAAoB,CAC1C,iBAAiB,CACC,CAAC;QACrB,MAAM,OAAO,GAAG;YACd,QAAQ,EAAE,EAAE,UAAU,EAAE,IAAA,mCAAyB,EAAC,IAAI,CAAC,SAAS,CAAC,EAAE;YACnE,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;YACzC,cAAc,EAAE,UAAU,CAAC,GAAG,CAC5B,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,IAAI,IAAI,eAAe,CAC5C;SACF,CAAC;QACF,OAAO,IAAA,uBAAa,EAClB,qBAAqB,EACrB,OAAO,EACP,KAAK,EACL,OAAO,EACP,OAAO,CACR,CAAC;IACJ,CAAC;CACF;AA5HD,kDA4HC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const processors = this._activeSpanProcessor[\n '_spanProcessors'\n ] as SpanProcessor[];\n const payload = {\n resource: { attributes: settledResourceAttributes(this._resource) },\n tracers: Array.from(this._tracers.keys()),\n spanProcessors: processors.map(\n p => p.constructor?.name ?? 'SpanProcessor'\n ),\n };\n return formatInspect(\n 'BasicTracerProvider',\n payload,\n depth,\n options,\n inspect\n );\n }\n}\n"]}
export declare const ExceptionEventName = "exception";
//# sourceMappingURL=enums.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExceptionEventName = void 0;
// Event name definitions
exports.ExceptionEventName = 'exception';
//# sourceMappingURL=enums.js.map
{"version":3,"file":"enums.js","sourceRoot":"","sources":["../../src/enums.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,yBAAyB;AACZ,QAAA,kBAAkB,GAAG,WAAW,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n"]}
import type { Context } from '@opentelemetry/api';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
import type { BufferConfig } from '../types';
import type { ReadableSpan } from './ReadableSpan';
import type { SpanExporter } from './SpanExporter';
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
export declare abstract class BatchSpanProcessorBase<T extends BufferConfig> implements SpanProcessor {
private readonly _maxExportBatchSize;
private readonly _maxQueueSize;
private readonly _scheduledDelayMillis;
private readonly _exportTimeoutMillis;
private readonly _exporter;
private _isExporting;
private _finishedSpans;
private _timer;
private _shutdownOnce;
private _droppedSpansCount;
constructor(exporter: SpanExporter, config?: T);
forceFlush(): Promise<void>;
onStart(_span: Span, _parentContext: Context): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
private _shutdown;
/** Add a span in the buffer. */
private _addToBuffer;
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
private _flushAll;
private _flushOneBatch;
private _maybeStartTimer;
private _clearTimer;
protected abstract onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessorBase.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchSpanProcessorBase = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
class BatchSpanProcessorBase {
_maxExportBatchSize;
_maxQueueSize;
_scheduledDelayMillis;
_exportTimeoutMillis;
_exporter;
_isExporting = false;
_finishedSpans = [];
_timer;
_shutdownOnce;
_droppedSpansCount = 0;
constructor(exporter, config) {
this._exporter = exporter;
this._maxExportBatchSize =
typeof config?.maxExportBatchSize === 'number'
? config.maxExportBatchSize
: ((0, core_1.getNumberFromEnv)('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);
this._maxQueueSize =
typeof config?.maxQueueSize === 'number'
? config.maxQueueSize
: ((0, core_1.getNumberFromEnv)('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);
this._scheduledDelayMillis =
typeof config?.scheduledDelayMillis === 'number'
? config.scheduledDelayMillis
: ((0, core_1.getNumberFromEnv)('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);
this._exportTimeoutMillis =
typeof config?.exportTimeoutMillis === 'number'
? config.exportTimeoutMillis
: ((0, core_1.getNumberFromEnv)('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);
this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
if (this._maxExportBatchSize > this._maxQueueSize) {
api_1.diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize');
this._maxExportBatchSize = this._maxQueueSize;
}
}
forceFlush() {
if (this._shutdownOnce.isCalled) {
return this._shutdownOnce.promise;
}
return this._flushAll();
}
// does nothing.
onStart(_span, _parentContext) { }
onEnd(span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) {
return;
}
this._addToBuffer(span);
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return Promise.resolve()
.then(() => {
return this.onShutdown();
})
.then(() => {
return this._flushAll();
})
.then(() => {
return this._exporter.shutdown();
});
}
/** Add a span in the buffer. */
_addToBuffer(span) {
if (this._finishedSpans.length >= this._maxQueueSize) {
// limit reached, drop span
if (this._droppedSpansCount === 0) {
api_1.diag.debug('maxQueueSize reached, dropping spans');
}
this._droppedSpansCount++;
return;
}
if (this._droppedSpansCount > 0) {
// some spans were dropped, log once with count of spans dropped
api_1.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
this._droppedSpansCount = 0;
}
this._finishedSpans.push(span);
this._maybeStartTimer();
}
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
_flushAll() {
return new Promise((resolve, reject) => {
const promises = [];
// calculate number of batches
const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
for (let i = 0, j = count; i < j; i++) {
promises.push(this._flushOneBatch());
}
Promise.all(promises)
.then(() => {
resolve();
})
.catch(reject);
});
}
_flushOneBatch() {
this._clearTimer();
if (this._finishedSpans.length === 0) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
// don't wait anymore for export, this way the next batch can start
reject(new Error('Timeout'));
}, this._exportTimeoutMillis);
// prevent downstream exporter calls from generating spans
api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => {
// Reset the finished spans buffer here because the next invocations of the _flush method
// could pass the same finished spans to the exporter if the buffer is cleared
// outside the execution of this callback.
let spans;
if (this._finishedSpans.length <= this._maxExportBatchSize) {
spans = this._finishedSpans;
this._finishedSpans = [];
}
else {
spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
}
const doExport = () => this._exporter.export(spans, result => {
clearTimeout(timer);
if (result.code === core_1.ExportResultCode.SUCCESS) {
resolve();
}
else {
reject(result.error ??
new Error('BatchSpanProcessor: span export failed'));
}
});
let pendingResources = null;
for (let i = 0, len = spans.length; i < len; i++) {
const span = spans[i];
if (span.resource.asyncAttributesPending &&
span.resource.waitForAsyncAttributes) {
pendingResources ??= [];
pendingResources.push(span.resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources === null) {
doExport();
}
else {
Promise.all(pendingResources).then(doExport, err => {
(0, core_1.globalErrorHandler)(err);
reject(err);
});
}
});
});
}
_maybeStartTimer() {
if (this._isExporting)
return;
const flush = () => {
this._isExporting = true;
this._flushOneBatch()
.finally(() => {
this._isExporting = false;
if (this._finishedSpans.length > 0) {
this._clearTimer();
this._maybeStartTimer();
}
})
.catch(e => {
this._isExporting = false;
(0, core_1.globalErrorHandler)(e);
});
};
// we only wait if the queue doesn't have enough elements yet
if (this._finishedSpans.length >= this._maxExportBatchSize) {
return flush();
}
if (this._timer !== undefined)
return;
this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
// depending on runtime, this may be a 'number' or NodeJS.Timeout
if (typeof this._timer !== 'number') {
this._timer.unref();
}
}
_clearTimer() {
if (this._timer !== undefined) {
clearTimeout(this._timer);
this._timer = undefined;
}
}
}
exports.BatchSpanProcessorBase = BatchSpanProcessorBase;
//# sourceMappingURL=BatchSpanProcessorBase.js.map
{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,4CAA+D;AAC/D,8CAM6B;AAO7B;;;GAGG;AACH,MAAsB,sBAAsB;IAGzB,mBAAmB,CAAS;IAC5B,aAAa,CAAS;IACtB,qBAAqB,CAAS;IAC9B,oBAAoB,CAAS;IAC7B,SAAS,CAAe;IAEjC,YAAY,GAAG,KAAK,CAAC;IACrB,cAAc,GAAmB,EAAE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AE,OAAO;QACtC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,qBAAqB,CAAC,CAAC;QAEpE,iEAAiE;QACjE,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;SACrB;IACH,CAAC;IAEO,WAAW;QACjB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;CAGF;AAtOD,wDAsOC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BufferConfig } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n"]}
import type { SpanExporter } from './SpanExporter';
import type { ReadableSpan } from './ReadableSpan';
import type { ExportResult } from '@opentelemetry/core';
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
export declare class ConsoleSpanExporter implements SpanExporter {
/**
* Export spans.
* @param spans
* @param resultCallback
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown the exporter.
*/
shutdown(): Promise<void>;
/**
* Exports any pending spans in exporter
*/
forceFlush(): Promise<void>;
/**
* converts span info into more readable format
* @param span
*/
private _exportInfo;
/**
* Showing spans in console
* @param spans
* @param done
*/
private _sendSpans;
}
//# sourceMappingURL=ConsoleSpanExporter.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConsoleSpanExporter = void 0;
const core_1 = require("@opentelemetry/core");
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
class ConsoleSpanExporter {
/**
* Export spans.
* @param spans
* @param resultCallback
*/
export(spans, resultCallback) {
return this._sendSpans(spans, resultCallback);
}
/**
* Shutdown the exporter.
*/
shutdown() {
this._sendSpans([]);
return this.forceFlush();
}
/**
* Exports any pending spans in exporter
*/
forceFlush() {
return Promise.resolve();
}
/**
* converts span info into more readable format
* @param span
*/
_exportInfo(span) {
return {
resource: {
attributes: span.resource.attributes,
},
instrumentationScope: span.instrumentationScope,
traceId: span.spanContext().traceId,
parentSpanContext: span.parentSpanContext,
traceState: span.spanContext().traceState?.serialize(),
name: span.name,
id: span.spanContext().spanId,
kind: span.kind,
timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime),
duration: (0, core_1.hrTimeToMicroseconds)(span.duration),
attributes: span.attributes,
status: span.status,
events: span.events,
links: span.links,
};
}
/**
* Showing spans in console
* @param spans
* @param done
*/
_sendSpans(spans, done) {
for (const span of spans) {
console.dir(this._exportInfo(span), { depth: 3 });
}
if (done) {
return done({ code: core_1.ExportResultCode.SUCCESS });
}
}
}
exports.ConsoleSpanExporter = ConsoleSpanExporter;
//# sourceMappingURL=ConsoleSpanExporter.js.map
{"version":3,"file":"ConsoleSpanExporter.js","sourceRoot":"","sources":["../../../src/export/ConsoleSpanExporter.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAKH,8CAA6E;AAE7E;;;;;GAKG;AAEH,+BAA+B;AAC/B,MAAa,mBAAmB;IAC9B;;;;OAIG;IACH,MAAM,CACJ,KAAqB,EACrB,cAA8C;QAE9C,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,IAAI,CAAC,UAAU,CAAC,EAAE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C;CACF;AArED,kDAqEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from './SpanExporter';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';\n\n/**\n * This is implementation of {@link SpanExporter} that prints spans to the\n * console. This class can be used for diagnostic purposes.\n *\n * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleSpanExporter implements SpanExporter {\n /**\n * Export spans.\n * @param spans\n * @param resultCallback\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n return this._sendSpans(spans, resultCallback);\n }\n\n /**\n * Shutdown the exporter.\n */\n shutdown(): Promise<void> {\n this._sendSpans([]);\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * converts span info into more readable format\n * @param span\n */\n private _exportInfo(span: ReadableSpan) {\n return {\n resource: {\n attributes: span.resource.attributes,\n },\n instrumentationScope: span.instrumentationScope,\n traceId: span.spanContext().traceId,\n parentSpanContext: span.parentSpanContext,\n traceState: span.spanContext().traceState?.serialize(),\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: hrTimeToMicroseconds(span.startTime),\n duration: hrTimeToMicroseconds(span.duration),\n attributes: span.attributes,\n status: span.status,\n events: span.events,\n links: span.links,\n };\n }\n\n /**\n * Showing spans in console\n * @param spans\n * @param done\n */\n private _sendSpans(\n spans: ReadableSpan[],\n done?: (result: ExportResult) => void\n ): void {\n for (const span of spans) {\n console.dir(this._exportInfo(span), { depth: 3 });\n }\n if (done) {\n return done({ code: ExportResultCode.SUCCESS });\n }\n }\n}\n"]}
import type { SpanExporter } from './SpanExporter';
import type { ReadableSpan } from './ReadableSpan';
import type { ExportResult } from '@opentelemetry/core';
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
export declare class InMemorySpanExporter implements SpanExporter {
private _finishedSpans;
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
protected _stopped: boolean;
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
shutdown(): Promise<void>;
/**
* Exports any pending spans in the exporter
*/
forceFlush(): Promise<void>;
reset(): void;
getFinishedSpans(): ReadableSpan[];
}
//# sourceMappingURL=InMemorySpanExporter.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemorySpanExporter = void 0;
const core_1 = require("@opentelemetry/core");
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
class InMemorySpanExporter {
_finishedSpans = [];
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
_stopped = false;
export(spans, resultCallback) {
if (this._stopped)
return resultCallback({
code: core_1.ExportResultCode.FAILED,
error: new Error('Exporter has been stopped'),
});
this._finishedSpans.push(...spans);
setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0);
}
shutdown() {
this._stopped = true;
this._finishedSpans = [];
return this.forceFlush();
}
/**
* Exports any pending spans in the exporter
*/
forceFlush() {
return Promise.resolve();
}
reset() {
this._finishedSpans = [];
}
getFinishedSpans() {
return this._finishedSpans;
}
}
exports.InMemorySpanExporter = InMemorySpanExporter;
//# sourceMappingURL=InMemorySpanExporter.js.map
{"version":3,"file":"InMemorySpanExporter.js","sourceRoot":"","sources":["../../../src/export/InMemorySpanExporter.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAKH,8CAAuD;AAEvD;;;;GAIG;AACH,MAAa,oBAAoB;IACvB,cAAc,GAAmB,EAAE,CAAC;IAC5C;;;OAGG;IACO,QAAQ,GAAG,KAAK,CAAC;IAE3B,MAAM,CACJ,KAAqB,EACrB,cAA8C;QAE9C,IAAI,IAAI,CAAC,QAAQ;YACf,OAAO,cAAc,CAAC;gBACpB,IAAI,EAAE,uBAAgB,CAAC,MAAM;gBAC7B,KAAK,EAAE,IAAI,KAAK,CAAC,2BAA2B,CAAC;aAC9C,CAAC,CAAC;QACL,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;QAEnC,UAAU,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,uBAAgB,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1E,CAAC;IAED,QAAQ;QACN,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;IAC3B,CAAC;IAED,gBAAgB;QACd,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;CACF;AA1CD,oDA0CC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from './SpanExporter';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\n\n/**\n * This class can be used for testing purposes. It stores the exported spans\n * in a list in memory that can be retrieved using the `getFinishedSpans()`\n * method.\n */\nexport class InMemorySpanExporter implements SpanExporter {\n private _finishedSpans: ReadableSpan[] = [];\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported spans will not be stored in-memory.\n */\n protected _stopped = false;\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._stopped)\n return resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n this._finishedSpans.push(...spans);\n\n setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);\n }\n\n shutdown(): Promise<void> {\n this._stopped = true;\n this._finishedSpans = [];\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n reset(): void {\n this._finishedSpans = [];\n }\n\n getFinishedSpans(): ReadableSpan[] {\n return this._finishedSpans;\n }\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './ReadableSpan';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
/** No-op implementation of SpanProcessor */
export declare class NoopSpanProcessor implements SpanProcessor {
onStart(_span: Span, _context: Context): void;
onEnd(_span: ReadableSpan): void;
shutdown(): Promise<void>;
forceFlush(): Promise<void>;
}
//# sourceMappingURL=NoopSpanProcessor.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopSpanProcessor = void 0;
/** No-op implementation of SpanProcessor */
class NoopSpanProcessor {
onStart(_span, _context) { }
onEnd(_span) { }
shutdown() {
return Promise.resolve();
}
forceFlush() {
return Promise.resolve();
}
}
exports.NoopSpanProcessor = NoopSpanProcessor;
//# sourceMappingURL=NoopSpanProcessor.js.map
{"version":3,"file":"NoopSpanProcessor.js","sourceRoot":"","sources":["../../../src/export/NoopSpanProcessor.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAOH,4CAA4C;AAC5C,MAAa,iBAAiB;IAC5B,OAAO,CAAC,KAAW,EAAE,QAAiB,IAAS,CAAC;IAChD,KAAK,CAAC,KAAmB,IAAS,CAAC;IACnC,QAAQ;QACN,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IACD,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF;AATD,8CASC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\n\n/** No-op implementation of SpanProcessor */\nexport class NoopSpanProcessor implements SpanProcessor {\n onStart(_span: Span, _context: Context): void {}\n onEnd(_span: ReadableSpan): void {}\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n"]}
import type { SpanKind, SpanStatus, Attributes, HrTime, Link, SpanContext } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { TimedEvent } from '../TimedEvent';
export interface ReadableSpan {
readonly name: string;
readonly kind: SpanKind;
readonly spanContext: () => SpanContext;
readonly parentSpanContext?: SpanContext;
readonly startTime: HrTime;
readonly endTime: HrTime;
readonly status: SpanStatus;
readonly attributes: Attributes;
readonly links: Link[];
readonly events: TimedEvent[];
readonly duration: HrTime;
readonly ended: boolean;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
readonly droppedAttributesCount: number;
readonly droppedEventsCount: number;
readonly droppedLinksCount: number;
}
//# sourceMappingURL=ReadableSpan.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=ReadableSpan.js.map
{"version":3,"file":"ReadableSpan.js","sourceRoot":"","sources":["../../../src/export/ReadableSpan.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n SpanKind,\n SpanStatus,\n Attributes,\n HrTime,\n Link,\n SpanContext,\n} from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { TimedEvent } from '../TimedEvent';\n\nexport interface ReadableSpan {\n readonly name: string;\n readonly kind: SpanKind;\n readonly spanContext: () => SpanContext;\n readonly parentSpanContext?: SpanContext;\n readonly startTime: HrTime;\n readonly endTime: HrTime;\n readonly status: SpanStatus;\n readonly attributes: Attributes;\n readonly links: Link[];\n readonly events: TimedEvent[];\n readonly duration: HrTime;\n readonly ended: boolean;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n readonly droppedAttributesCount: number;\n readonly droppedEventsCount: number;\n readonly droppedLinksCount: number;\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { Span } from '../Span';
import type { SpanProcessor } from '../SpanProcessor';
import type { ReadableSpan } from './ReadableSpan';
import type { SpanExporter } from './SpanExporter';
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
export declare class SimpleSpanProcessor implements SpanProcessor {
private readonly _exporter;
private _shutdownOnce;
private _pendingExports;
constructor(exporter: SpanExporter);
forceFlush(): Promise<void>;
onStart(_span: Span, _parentContext: Context): void;
onEnd(span: ReadableSpan): void;
private _doExport;
shutdown(): Promise<void>;
private _shutdown;
}
//# sourceMappingURL=SimpleSpanProcessor.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleSpanProcessor = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
class SimpleSpanProcessor {
_exporter;
_shutdownOnce;
_pendingExports;
constructor(exporter) {
this._exporter = exporter;
this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
this._pendingExports = new Set();
}
async forceFlush() {
await Promise.all(Array.from(this._pendingExports));
if (this._exporter.forceFlush) {
await this._exporter.forceFlush();
}
}
onStart(_span, _parentContext) { }
onEnd(span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) {
return;
}
const pendingExport = this._doExport(span).catch(err => (0, core_1.globalErrorHandler)(err));
// Enqueue this export to the pending list so it can be flushed by the user.
this._pendingExports.add(pendingExport);
void pendingExport.finally(() => this._pendingExports.delete(pendingExport));
}
async _doExport(span) {
if (span.resource.asyncAttributesPending) {
// Ensure resource is fully resolved before exporting.
await span.resource.waitForAsyncAttributes?.();
}
const result = await core_1.internal._export(this._exporter, [span]);
if (result.code !== core_1.ExportResultCode.SUCCESS) {
throw (result.error ??
new Error(`SimpleSpanProcessor: span export failed (status ${result})`));
}
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return this._exporter.shutdown();
}
}
exports.SimpleSpanProcessor = SimpleSpanProcessor;
//# sourceMappingURL=SimpleSpanProcessor.js.map
{"version":3,"file":"SimpleSpanProcessor.js","sourceRoot":"","sources":["../../../src/export/SimpleSpanProcessor.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,4CAAgD;AAChD,8CAK6B;AAM7B;;;;;;;GAOG;AACH,MAAa,mBAAmB;IACb,SAAS,CAAe;IACjC,aAAa,CAAuB;IACpC,eAAe,CAAqB;IAE5C,YAAY,QAAsB;QAChC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,aAAa,GAAG,IAAI,qBAAc,CAA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CAAC,CAAC;QAC9D,IAAI,MAAM,CAAC,IAAI,KAAK,uBAAgB,CAAC,OAAO,EAAE;YAC5C,MAAM,CACJ,MAAM,CAAC,KAAK;gBACZ,IAAI,KAAK,CAAC,mDAAmD,MAAM,GAAG,CAAC,CACxE,CAAC;SACH;IACH,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;IACnC,CAAC;IAEO,SAAS;QACf,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IACnC,CAAC;CACF;AA7DD,kDA6DC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { TraceFlags } from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n BindOnceFuture,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * An implementation of the {@link SpanProcessor} that converts the {@link Span}\n * to {@link ReadableSpan} and passes it to the configured exporter.\n *\n * Only spans that are sampled are converted.\n *\n * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.\n */\nexport class SimpleSpanProcessor implements SpanProcessor {\n private readonly _exporter: SpanExporter;\n private _shutdownOnce: BindOnceFuture<void>;\n private _pendingExports: Set<Promise<void>>;\n\n constructor(exporter: SpanExporter) {\n this._exporter = exporter;\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._pendingExports = new Set<Promise<void>>();\n }\n\n async forceFlush(): Promise<void> {\n await Promise.all(Array.from(this._pendingExports));\n if (this._exporter.forceFlush) {\n await this._exporter.forceFlush();\n }\n }\n\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n const pendingExport = this._doExport(span).catch(err =>\n globalErrorHandler(err)\n );\n // Enqueue this export to the pending list so it can be flushed by the user.\n this._pendingExports.add(pendingExport);\n void pendingExport.finally(() =>\n this._pendingExports.delete(pendingExport)\n );\n }\n\n private async _doExport(span: ReadableSpan): Promise<void> {\n if (span.resource.asyncAttributesPending) {\n // Ensure resource is fully resolved before exporting.\n await span.resource.waitForAsyncAttributes?.();\n }\n\n const result = await internal._export(this._exporter, [span]);\n if (result.code !== ExportResultCode.SUCCESS) {\n throw (\n result.error ??\n new Error(`SimpleSpanProcessor: span export failed (status ${result})`)\n );\n }\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n return this._exporter.shutdown();\n }\n}\n"]}
import type { ExportResult } from '@opentelemetry/core';
import type { ReadableSpan } from './ReadableSpan';
/**
* An interface that allows different tracing services to export recorded data
* for sampled spans in their own format.
*
* To export data this MUST be register to the Tracer SDK using a optional
* config.
*/
export interface SpanExporter {
/**
* Called to export sampled {@link ReadableSpan}s.
* @param spans the list of sampled Spans to be exported.
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/** Stops the exporter. */
shutdown(): Promise<void>;
/** Immediately export all spans */
forceFlush?(): Promise<void>;
}
//# sourceMappingURL=SpanExporter.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=SpanExporter.js.map
{"version":3,"file":"SpanExporter.js","sourceRoot":"","sources":["../../../src/export/SpanExporter.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport type { ReadableSpan } from './ReadableSpan';\n\n/**\n * An interface that allows different tracing services to export recorded data\n * for sampled spans in their own format.\n *\n * To export data this MUST be register to the Tracer SDK using a optional\n * config.\n */\nexport interface SpanExporter {\n /**\n * Called to export sampled {@link ReadableSpan}s.\n * @param spans the list of sampled Spans to be exported.\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void;\n\n /** Stops the exporter. */\n shutdown(): Promise<void>;\n\n /** Immediately export all spans */\n forceFlush?(): Promise<void>;\n}\n"]}
/** IdGenerator provides an interface for generating Trace Id and Span Id */
export interface IdGenerator {
/** Returns a trace ID composed of 32 lowercase hex characters. */
generateTraceId(): string;
/** Returns a span ID composed of 16 lowercase hex characters. */
generateSpanId(): string;
}
//# sourceMappingURL=IdGenerator.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IdGenerator.js.map
{"version":3,"file":"IdGenerator.js","sourceRoot":"","sources":["../../src/IdGenerator.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/** IdGenerator provides an interface for generating Trace Id and Span Id */\nexport interface IdGenerator {\n /** Returns a trace ID composed of 32 lowercase hex characters. */\n generateTraceId(): string;\n /** Returns a span ID composed of 16 lowercase hex characters. */\n generateSpanId(): string;\n}\n"]}
export { BasicTracerProvider } from './BasicTracerProvider';
export { BatchSpanProcessor, RandomIdGenerator } from './platform';
export { ConsoleSpanExporter } from './export/ConsoleSpanExporter';
export { InMemorySpanExporter } from './export/InMemorySpanExporter';
export type { ReadableSpan } from './export/ReadableSpan';
export { SimpleSpanProcessor } from './export/SimpleSpanProcessor';
export type { SpanExporter } from './export/SpanExporter';
export { NoopSpanProcessor } from './export/NoopSpanProcessor';
export { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
export { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
export { ParentBasedSampler } from './sampler/ParentBasedSampler';
export { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
export { SamplingDecision } from './Sampler';
export type { Sampler, SamplingResult } from './Sampler';
export type { Span } from './Span';
export type { SpanProcessor } from './SpanProcessor';
export type { TimedEvent } from './TimedEvent';
export type { BatchSpanProcessorBrowserConfig, BufferConfig, GeneralLimits, SDKRegistrationConfig, SpanLimits, TracerConfig, } from './types';
export type { IdGenerator } from './IdGenerator';
//# sourceMappingURL=index.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.SimpleSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.RandomIdGenerator = exports.BatchSpanProcessor = exports.BasicTracerProvider = void 0;
var BasicTracerProvider_1 = require("./BasicTracerProvider");
Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: function () { return BasicTracerProvider_1.BasicTracerProvider; } });
var platform_1 = require("./platform");
Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return platform_1.BatchSpanProcessor; } });
Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return platform_1.RandomIdGenerator; } });
var ConsoleSpanExporter_1 = require("./export/ConsoleSpanExporter");
Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: function () { return ConsoleSpanExporter_1.ConsoleSpanExporter; } });
var InMemorySpanExporter_1 = require("./export/InMemorySpanExporter");
Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: function () { return InMemorySpanExporter_1.InMemorySpanExporter; } });
var SimpleSpanProcessor_1 = require("./export/SimpleSpanProcessor");
Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: function () { return SimpleSpanProcessor_1.SimpleSpanProcessor; } });
var NoopSpanProcessor_1 = require("./export/NoopSpanProcessor");
Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: function () { return NoopSpanProcessor_1.NoopSpanProcessor; } });
var AlwaysOffSampler_1 = require("./sampler/AlwaysOffSampler");
Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: function () { return AlwaysOffSampler_1.AlwaysOffSampler; } });
var AlwaysOnSampler_1 = require("./sampler/AlwaysOnSampler");
Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: function () { return AlwaysOnSampler_1.AlwaysOnSampler; } });
var ParentBasedSampler_1 = require("./sampler/ParentBasedSampler");
Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: function () { return ParentBasedSampler_1.ParentBasedSampler; } });
var TraceIdRatioBasedSampler_1 = require("./sampler/TraceIdRatioBasedSampler");
Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: function () { return TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler; } });
var Sampler_1 = require("./Sampler");
Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return Sampler_1.SamplingDecision; } });
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,uCAAmE;AAA1D,8GAAA,kBAAkB,OAAA;AAAE,6GAAA,iBAAiB,OAAA;AAC9C,oEAAmE;AAA1D,0HAAA,mBAAmB,OAAA;AAC5B,sEAAqE;AAA5D,4HAAA,oBAAoB,OAAA;AAE7B,oEAAmE;AAA1D,0HAAA,mBAAmB,OAAA;AAE5B,gEAA+D;AAAtD,sHAAA,iBAAiB,OAAA;AAC1B,+DAA8D;AAArD,oHAAA,gBAAgB,OAAA;AACzB,6DAA4D;AAAnD,kHAAA,eAAe,OAAA;AACxB,mEAAkE;AAAzD,wHAAA,kBAAkB,OAAA;AAC3B,+EAA8E;AAArE,oIAAA,wBAAwB,OAAA;AACjC,qCAA6C;AAApC,2GAAA,gBAAgB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BasicTracerProvider } from './BasicTracerProvider';\nexport { BatchSpanProcessor, RandomIdGenerator } from './platform';\nexport { ConsoleSpanExporter } from './export/ConsoleSpanExporter';\nexport { InMemorySpanExporter } from './export/InMemorySpanExporter';\nexport type { ReadableSpan } from './export/ReadableSpan';\nexport { SimpleSpanProcessor } from './export/SimpleSpanProcessor';\nexport type { SpanExporter } from './export/SpanExporter';\nexport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nexport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nexport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nexport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nexport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\nexport { SamplingDecision } from './Sampler';\nexport type { Sampler, SamplingResult } from './Sampler';\nexport type { Span } from './Span';\nexport type { SpanProcessor } from './SpanProcessor';\nexport type { TimedEvent } from './TimedEvent';\nexport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n GeneralLimits,\n SDKRegistrationConfig,\n SpanLimits,\n TracerConfig,\n} from './types';\nexport type { IdGenerator } from './IdGenerator';\n"]}
import type { Attributes } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
/**
* Well-known symbol used by Node.js `util.inspect` (and `console.*`) to
* render an object via a custom representation. Defined as a global Symbol
* so it works without importing from `node:util`, keeping this module safe
* for browser builds (where the symbol is simply never looked up).
*/
export declare const inspectCustom: unique symbol;
/**
* Collect a Resource's settled attributes without touching the
* `attributes` getter, which emits diag.error/debug entries when async
* attribute detectors are still pending. Promise-like (unsettled)
* entries are silently skipped so logging a Span/Tracer/Provider during
* startup doesn't recurse through the diag pipeline.
*/
export declare function settledResourceAttributes(resource: Resource): Attributes;
export type InspectFn = (value: unknown, options: unknown) => string;
export interface InspectStylizeOptions {
depth?: number | null;
stylize?: (text: string, styleType: string) => string;
}
/**
* Build a class-tagged inspect representation. Returns a stub like
* `[ClassName]` once the recursion budget is exhausted, otherwise returns
* `ClassName <inspected payload>` so nested fields keep proper coloring,
* indentation, and depth handling. In environments that don't supply an
* `inspect` callback (e.g. browsers), falls back to returning the raw
* payload object.
*/
export declare function formatInspect(className: string, payload: object, depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
//# sourceMappingURL=inspect.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatInspect = exports.settledResourceAttributes = exports.inspectCustom = void 0;
/**
* Well-known symbol used by Node.js `util.inspect` (and `console.*`) to
* render an object via a custom representation. Defined as a global Symbol
* so it works without importing from `node:util`, keeping this module safe
* for browser builds (where the symbol is simply never looked up).
*/
exports.inspectCustom = Symbol.for('nodejs.util.inspect.custom');
/**
* Collect a Resource's settled attributes without touching the
* `attributes` getter, which emits diag.error/debug entries when async
* attribute detectors are still pending. Promise-like (unsettled)
* entries are silently skipped so logging a Span/Tracer/Provider during
* startup doesn't recurse through the diag pipeline.
*/
function settledResourceAttributes(resource) {
const attrs = {};
for (const [k, v] of resource.getRawAttributes()) {
if (typeof v?.then === 'function') {
continue;
}
if (v != null) {
attrs[k] ??= v;
}
}
return attrs;
}
exports.settledResourceAttributes = settledResourceAttributes;
/**
* Build a class-tagged inspect representation. Returns a stub like
* `[ClassName]` once the recursion budget is exhausted, otherwise returns
* `ClassName <inspected payload>` so nested fields keep proper coloring,
* indentation, and depth handling. In environments that don't supply an
* `inspect` callback (e.g. browsers), falls back to returning the raw
* payload object.
*/
function formatInspect(className, payload, depth, options, inspect) {
if (typeof depth === 'number' && depth < 0) {
const tag = `[${className}]`;
return options?.stylize ? options.stylize(tag, 'special') : tag;
}
if (typeof inspect !== 'function' || !options) {
return payload;
}
const childOptions = {
...options,
depth: options.depth == null ? options.depth : options.depth - 1,
};
return `${className} ${inspect(payload, childOptions)}`;
}
exports.formatInspect = formatInspect;
//# sourceMappingURL=inspect.js.map
{"version":3,"file":"inspect.js","sourceRoot":"","sources":["../../src/inspect.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAKH;;;;;GAKG;AACU,QAAA,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAEtE;;;;;;GAMG;AACH,SAAgB,yBAAyB,CAAC,QAAkB;IAC1D,MAAM,KAAK,GAAe,EAAE,CAAC;IAC7B,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,QAAQ,CAAC,gBAAgB,EAAE,EAAE;QAChD,IAAI,OAAQ,CAAmC,EAAE,IAAI,KAAK,UAAU,EAAE;YACpE,SAAS;SACV;QACD,IAAI,CAAC,IAAI,IAAI,EAAE;YACb,KAAK,CAAC,CAAC,CAAC,KAAK,CAAmB,CAAC;SAClC;KACF;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAXD,8DAWC;AASD;;;;;;;GAOG;AACH,SAAgB,aAAa,CAC3B,SAAiB,EACjB,OAAe,EACf,KAAa,EACb,OAA0C,EAC1C,OAA8B;IAE9B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,GAAG,CAAC,EAAE;QAC1C,MAAM,GAAG,GAAG,IAAI,SAAS,GAAG,CAAC;QAC7B,OAAO,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;KACjE;IACD,IAAI,OAAO,OAAO,KAAK,UAAU,IAAI,CAAC,OAAO,EAAE;QAC7C,OAAO,OAAO,CAAC;KAChB;IACD,MAAM,YAAY,GAAG;QACnB,GAAG,OAAO;QACV,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,GAAG,CAAC;KACjE,CAAC;IACF,OAAO,GAAG,SAAS,IAAI,OAAO,CAAC,OAAO,EAAE,YAAY,CAAC,EAAE,CAAC;AAC1D,CAAC;AAnBD,sCAmBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\n\n/**\n * Well-known symbol used by Node.js `util.inspect` (and `console.*`) to\n * render an object via a custom representation. Defined as a global Symbol\n * so it works without importing from `node:util`, keeping this module safe\n * for browser builds (where the symbol is simply never looked up).\n */\nexport const inspectCustom = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * Collect a Resource's settled attributes without touching the\n * `attributes` getter, which emits diag.error/debug entries when async\n * attribute detectors are still pending. Promise-like (unsettled)\n * entries are silently skipped so logging a Span/Tracer/Provider during\n * startup doesn't recurse through the diag pipeline.\n */\nexport function settledResourceAttributes(resource: Resource): Attributes {\n const attrs: Attributes = {};\n for (const [k, v] of resource.getRawAttributes()) {\n if (typeof (v as Partial<PromiseLike<unknown>>)?.then === 'function') {\n continue;\n }\n if (v != null) {\n attrs[k] ??= v as AttributeValue;\n }\n }\n return attrs;\n}\n\nexport type InspectFn = (value: unknown, options: unknown) => string;\n\nexport interface InspectStylizeOptions {\n depth?: number | null;\n stylize?: (text: string, styleType: string) => string;\n}\n\n/**\n * Build a class-tagged inspect representation. Returns a stub like\n * `[ClassName]` once the recursion budget is exhausted, otherwise returns\n * `ClassName <inspected payload>` so nested fields keep proper coloring,\n * indentation, and depth handling. In environments that don't supply an\n * `inspect` callback (e.g. browsers), falls back to returning the raw\n * payload object.\n */\nexport function formatInspect(\n className: string,\n payload: object,\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n): unknown {\n if (typeof depth === 'number' && depth < 0) {\n const tag = `[${className}]`;\n return options?.stylize ? options.stylize(tag, 'special') : tag;\n }\n if (typeof inspect !== 'function' || !options) {\n return payload;\n }\n const childOptions = {\n ...options,\n depth: options.depth == null ? options.depth : options.depth - 1,\n };\n return `${className} ${inspect(payload, childOptions)}`;\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './export/ReadableSpan';
import type { Span } from './Span';
import type { SpanProcessor } from './SpanProcessor';
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
export declare class MultiSpanProcessor implements SpanProcessor {
private readonly _spanProcessors;
constructor(spanProcessors: SpanProcessor[]);
forceFlush(): Promise<void>;
onStart(span: Span, context: Context): void;
onEnding(span: Span): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
}
//# sourceMappingURL=MultiSpanProcessor.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultiSpanProcessor = void 0;
const core_1 = require("@opentelemetry/core");
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
class MultiSpanProcessor {
_spanProcessors;
constructor(spanProcessors) {
this._spanProcessors = spanProcessors;
}
forceFlush() {
const promises = [];
for (const spanProcessor of this._spanProcessors) {
promises.push(spanProcessor.forceFlush());
}
return new Promise(resolve => {
Promise.all(promises)
.then(() => {
resolve();
})
.catch(error => {
(0, core_1.globalErrorHandler)(error || new Error('MultiSpanProcessor: forceFlush failed'));
resolve();
});
});
}
onStart(span, context) {
for (const spanProcessor of this._spanProcessors) {
spanProcessor.onStart(span, context);
}
}
onEnding(span) {
for (const spanProcessor of this._spanProcessors) {
if (spanProcessor.onEnding) {
spanProcessor.onEnding(span);
}
}
}
onEnd(span) {
for (const spanProcessor of this._spanProcessors) {
spanProcessor.onEnd(span);
}
}
shutdown() {
const promises = [];
for (const spanProcessor of this._spanProcessors) {
promises.push(spanProcessor.shutdown());
}
return new Promise((resolve, reject) => {
Promise.all(promises).then(() => {
resolve();
}, reject);
});
}
}
exports.MultiSpanProcessor = MultiSpanProcessor;
//# sourceMappingURL=MultiSpanProcessor.js.map
{"version":3,"file":"MultiSpanProcessor.js","sourceRoot":"","sources":["../../src/MultiSpanProcessor.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,8CAAyD;AAKzD;;;GAGG;AACH,MAAa,kBAAkB;IACZ,eAAe,CAAkB;IAClD,YAAY,cAA+B;QACzC,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;IACxC,CAAC;IAED,UAAU;QACR,MAAM,QAAQ,GAAoB,EAAE,CAAC;QAErC,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC,CAAC;SAC3C;QACD,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YAC3B,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;iBAClB,IAAI,CAAC,GAAG,EAAE;gBACT,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC;iBACD,KAAK,CAAC,KAAK,CAAC,EAAE;gBACb,IAAA,yBAAkB,EAChB,KAAK,IAAI,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAC5D,CAAC;gBACF,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,CAAC,IAAU,EAAE,OAAgB;QAClC,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,aAAa,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;SACtC;IACH,CAAC;IAED,QAAQ,CAAC,IAAU;QACjB,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,IAAI,aAAa,CAAC,QAAQ,EAAE;gBAC1B,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;aAC9B;SACF;IACH,CAAC;IAED,KAAK,CAAC,IAAkB;QACtB,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SAC3B;IACH,CAAC;IAED,QAAQ;QACN,MAAM,QAAQ,GAAoB,EAAE,CAAC;QAErC,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,eAAe,EAAE;YAChD,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC,CAAC;SACzC;QACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;gBAC9B,OAAO,EAAE,CAAC;YACZ,CAAC,EAAE,MAAM,CAAC,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA1DD,gDA0DC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n"]}
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import type { SpanExporter } from '../../../export/SpanExporter';
import type { BatchSpanProcessorBrowserConfig } from '../../../types';
export declare class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {
private _visibilityChangeListener?;
private _pageHideListener?;
constructor(_exporter: SpanExporter, config?: BatchSpanProcessorBrowserConfig);
private onInit;
protected onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessor.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchSpanProcessor = void 0;
const BatchSpanProcessorBase_1 = require("../../../export/BatchSpanProcessorBase");
const core_1 = require("@opentelemetry/core");
class BatchSpanProcessor extends BatchSpanProcessorBase_1.BatchSpanProcessorBase {
_visibilityChangeListener;
_pageHideListener;
constructor(_exporter, config) {
super(_exporter, config);
this.onInit(config);
}
onInit(config) {
if (config?.disableAutoFlushOnDocumentHide !== true &&
typeof document !== 'undefined') {
this._visibilityChangeListener = () => {
if (document.visibilityState === 'hidden') {
this.forceFlush().catch(error => {
(0, core_1.globalErrorHandler)(error);
});
}
};
this._pageHideListener = () => {
this.forceFlush().catch(error => {
(0, core_1.globalErrorHandler)(error);
});
};
document.addEventListener('visibilitychange', this._visibilityChangeListener);
// use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769
document.addEventListener('pagehide', this._pageHideListener);
}
}
onShutdown() {
if (typeof document !== 'undefined') {
if (this._visibilityChangeListener) {
document.removeEventListener('visibilitychange', this._visibilityChangeListener);
}
if (this._pageHideListener) {
document.removeEventListener('pagehide', this._pageHideListener);
}
}
}
}
exports.BatchSpanProcessor = BatchSpanProcessor;
//# sourceMappingURL=BatchSpanProcessor.js.map
{"version":3,"file":"BatchSpanProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/browser/export/BatchSpanProcessor.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,mFAAgF;AAGhF,8CAAyD;AAEzD,MAAa,kBAAmB,SAAQ,+CAAuD;IACrF,yBAAyB,CAAc;IACvC,iBAAiB,CAAc;IAEvC,YACE,SAAuB,EACvB,MAAwC;QAExC,KAAK,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QACzB,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IAEO,MAAM,CAAC,MAAwC;QACrD,IACE,MAAM,EAAE,8BAA8B,KAAK,IAAI;YAC/C,OAAO,QAAQ,KAAK,WAAW,EAC/B;YACA,IAAI,CAAC,yBAAyB,GAAG,GAAG,EAAE;gBACpC,IAAI,QAAQ,CAAC,eAAe,KAAK,QAAQ,EAAE;oBACzC,IAAI,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;wBAC9B,IAAA,yBAAkB,EAAC,KAAK,CAAC,CAAC;oBAC5B,CAAC,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC;YACF,IAAI,CAAC,iBAAiB,GAAG,GAAG,EAAE;gBAC5B,IAAI,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;oBAC9B,IAAA,yBAAkB,EAAC,KAAK,CAAC,CAAC;gBAC5B,CAAC,CAAC,CAAC;YACL,CAAC,CAAC;YACF,QAAQ,CAAC,gBAAgB,CACvB,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;YAEF,oGAAoG;YACpG,QAAQ,CAAC,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;SAC/D;IACH,CAAC;IAES,UAAU;QAClB,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;YACnC,IAAI,IAAI,CAAC,yBAAyB,EAAE;gBAClC,QAAQ,CAAC,mBAAmB,CAC1B,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;aACH;YACD,IAAI,IAAI,CAAC,iBAAiB,EAAE;gBAC1B,QAAQ,CAAC,mBAAmB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;aAClE;SACF;IACH,CAAC;CACF;AApDD,gDAoDC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { SpanExporter } from '../../../export/SpanExporter';\nimport type { BatchSpanProcessorBrowserConfig } from '../../../types';\nimport { globalErrorHandler } from '@opentelemetry/core';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {\n private _visibilityChangeListener?: () => void;\n private _pageHideListener?: () => void;\n\n constructor(\n _exporter: SpanExporter,\n config?: BatchSpanProcessorBrowserConfig\n ) {\n super(_exporter, config);\n this.onInit(config);\n }\n\n private onInit(config?: BatchSpanProcessorBrowserConfig): void {\n if (\n config?.disableAutoFlushOnDocumentHide !== true &&\n typeof document !== 'undefined'\n ) {\n this._visibilityChangeListener = () => {\n if (document.visibilityState === 'hidden') {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n }\n };\n this._pageHideListener = () => {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n };\n document.addEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n\n // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769\n document.addEventListener('pagehide', this._pageHideListener);\n }\n }\n\n protected onShutdown(): void {\n if (typeof document !== 'undefined') {\n if (this._visibilityChangeListener) {\n document.removeEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n }\n if (this._pageHideListener) {\n document.removeEventListener('pagehide', this._pageHideListener);\n }\n }\n }\n}\n"]}
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0;
var BatchSpanProcessor_1 = require("./export/BatchSpanProcessor");
Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return BatchSpanProcessor_1.BatchSpanProcessor; } });
var RandomIdGenerator_1 = require("./RandomIdGenerator");
Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return RandomIdGenerator_1.RandomIdGenerator; } });
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,kEAAiE;AAAxD,wHAAA,kBAAkB,OAAA;AAC3B,yDAAwD;AAA/C,sHAAA,iBAAiB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n"]}
import type { IdGenerator } from '../../IdGenerator';
export declare class RandomIdGenerator implements IdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId(): string;
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId(): string;
}
//# sourceMappingURL=RandomIdGenerator.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RandomIdGenerator = void 0;
const TRACE_ID_BYTES = 16;
const SPAN_ID_BYTES = 8;
const TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);
const SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);
// Byte-to-hex lookup is faster than toString(16) in browsers
const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
* Fills buffer with random bytes, ensuring at least one is non-zero
* per W3C Trace Context spec.
*/
function randomFill(buf) {
for (let i = 0; i < buf.length; i++) {
buf[i] = (Math.random() * 256) >>> 0;
}
// Ensure non-zero
for (let i = 0; i < buf.length; i++) {
if (buf[i] > 0)
return;
}
buf[buf.length - 1] = 1;
}
function toHex(buf) {
let hex = '';
for (let i = 0; i < buf.length; i++) {
hex += HEX[buf[i]];
}
return hex;
}
class RandomIdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId() {
randomFill(TRACE_BUFFER);
return toHex(TRACE_BUFFER);
}
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId() {
randomFill(SPAN_BUFFER);
return toHex(SPAN_BUFFER);
}
}
exports.RandomIdGenerator = RandomIdGenerator;
//# sourceMappingURL=RandomIdGenerator.js.map
{"version":3,"file":"RandomIdGenerator.js","sourceRoot":"","sources":["../../../../src/platform/browser/RandomIdGenerator.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAIH,MAAM,cAAc,GAAG,EAAE,CAAC;AAC1B,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,MAAM,YAAY,GAAG,IAAI,UAAU,CAAC,cAAc,CA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,cAAc;QACZ,UAAU,CAAC,WAAW,CAAC,CAAC;QACxB,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC;IAC5B,CAAC;CACF;AAlBD,8CAkBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst TRACE_ID_BYTES = 16;\nconst SPAN_ID_BYTES = 8;\n\nconst TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);\nconst SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);\n\n// Byte-to-hex lookup is faster than toString(16) in browsers\nconst HEX: string[] = Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Fills buffer with random bytes, ensuring at least one is non-zero\n * per W3C Trace Context spec.\n */\nfunction randomFill(buf: Uint8Array): void {\n for (let i = 0; i < buf.length; i++) {\n buf[i] = (Math.random() * 256) >>> 0;\n }\n // Ensure non-zero\n for (let i = 0; i < buf.length; i++) {\n if (buf[i] > 0) return;\n }\n buf[buf.length - 1] = 1;\n}\n\nfunction toHex(buf: Uint8Array): string {\n let hex = '';\n for (let i = 0; i < buf.length; i++) {\n hex += HEX[buf[i]];\n }\n return hex;\n}\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId(): string {\n randomFill(TRACE_BUFFER);\n return toHex(TRACE_BUFFER);\n }\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId(): string {\n randomFill(SPAN_BUFFER);\n return toHex(SPAN_BUFFER);\n }\n}\n"]}
export { BatchSpanProcessor, RandomIdGenerator } from './node';
//# sourceMappingURL=index.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0;
var node_1 = require("./node");
Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return node_1.BatchSpanProcessor; } });
Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return node_1.RandomIdGenerator; } });
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+BAA+D;AAAtD,0GAAA,kBAAkB,OAAA;AAAE,yGAAA,iBAAiB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor, RandomIdGenerator } from './node';\n"]}
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import type { BufferConfig } from '../../../types';
export declare class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {
protected onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessor.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchSpanProcessor = void 0;
const BatchSpanProcessorBase_1 = require("../../../export/BatchSpanProcessorBase");
class BatchSpanProcessor extends BatchSpanProcessorBase_1.BatchSpanProcessorBase {
onShutdown() { }
}
exports.BatchSpanProcessor = BatchSpanProcessor;
//# sourceMappingURL=BatchSpanProcessor.js.map
{"version":3,"file":"BatchSpanProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/node/export/BatchSpanProcessor.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,mFAAgF;AAGhF,MAAa,kBAAmB,SAAQ,+CAAoC;IAChE,UAAU,KAAU,CAAC;CAChC;AAFD,gDAEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n"]}
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0;
var BatchSpanProcessor_1 = require("./export/BatchSpanProcessor");
Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return BatchSpanProcessor_1.BatchSpanProcessor; } });
var RandomIdGenerator_1 = require("./RandomIdGenerator");
Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return RandomIdGenerator_1.RandomIdGenerator; } });
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,kEAAiE;AAAxD,wHAAA,kBAAkB,OAAA;AAC3B,yDAAwD;AAA/C,sHAAA,iBAAiB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n"]}
import type { IdGenerator } from '../../IdGenerator';
export declare class RandomIdGenerator implements IdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId: () => string;
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId: () => string;
}
//# sourceMappingURL=RandomIdGenerator.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RandomIdGenerator = void 0;
const SPAN_ID_BYTES = 8;
const TRACE_ID_BYTES = 16;
class RandomIdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId = getIdGenerator(TRACE_ID_BYTES);
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId = getIdGenerator(SPAN_ID_BYTES);
}
exports.RandomIdGenerator = RandomIdGenerator;
const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
function getIdGenerator(bytes) {
return function generateId() {
for (let i = 0; i < bytes / 4; i++) {
// unsigned right shift drops decimal part of the number
// it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE
SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);
}
// If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated
for (let i = 0; i < bytes; i++) {
if (SHARED_BUFFER[i] > 0) {
break;
}
else if (i === bytes - 1) {
SHARED_BUFFER[bytes - 1] = 1;
}
}
return SHARED_BUFFER.toString('hex', 0, bytes);
};
}
//# sourceMappingURL=RandomIdGenerator.js.map
{"version":3,"file":"RandomIdGenerator.js","sourceRoot":"","sources":["../../../../src/platform/node/RandomIdGenerator.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAIH,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,cAAc,GAAG,EAAE,CAAC;AAE1B,MAAa,iBAAiB;IAC5B;;;OAGG;IACH,eAAe,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;IAEjD;;;OAGG;IACH,cAAc,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;CAChD;AAZD,8CAYC;AAED,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;AACzD,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,SAAS,UAAU;QACxB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YAClC,wDAAwD;YACxD,gIAAgI;YAChI,aAAa,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;SACrE;QAED,sFAAsF;QACtF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YAC9B,IAAI,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE;gBACxB,MAAM;aACP;iBAAM,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE;gBAC1B,aAAa,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;aAC9B;SACF;QAED,OAAO,aAAa,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n"]}
import type { Context, Link, Attributes, SpanKind, TraceState } from '@opentelemetry/api';
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
export declare enum SamplingDecision {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
NOT_RECORD = 0,
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
RECORD = 1,
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
RECORD_AND_SAMPLED = 2
}
/**
* A sampling result contains a decision for a {@link Span} and additional
* attributes the sampler would like to added to the Span.
*/
export interface SamplingResult {
/**
* A sampling decision, refer to {@link SamplingDecision} for details.
*/
decision: SamplingDecision;
/**
* The list of attributes returned by SamplingResult MUST be immutable.
* Caller may call {@link Sampler}.shouldSample any number of times and
* can safely cache the returned value.
*/
attributes?: Readonly<Attributes>;
/**
* A {@link TraceState} that will be associated with the {@link Span} through
* the new {@link SpanContext}. Samplers SHOULD return the TraceState from
* the passed-in {@link Context} if they do not intend to change it. Leaving
* the value undefined will also leave the TraceState unchanged.
*/
traceState?: TraceState;
}
/**
* This interface represent a sampler. Sampling is a mechanism to control the
* noise and overhead introduced by OpenTelemetry by reducing the number of
* samples of traces collected and sent to the backend.
*/
export interface Sampler {
/**
* Checks whether span needs to be created and tracked.
*
* @param context Parent Context which may contain a span.
* @param traceId of the span to be created. It can be different from the
* traceId in the {@link SpanContext}. Typically in situations when the
* span to be created starts a new trace.
* @param spanName of the span to be created.
* @param spanKind of the span to be created.
* @param attributes Initial set of Attributes for the Span being constructed.
* @param links Collection of links that will be associated with the Span to
* be created. Typically useful for batch operations.
* @returns a {@link SamplingResult}.
*/
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: Attributes, links: Link[]): SamplingResult;
/** Returns the sampler name or short description with the configuration. */
toString(): string;
}
//# sourceMappingURL=Sampler.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamplingDecision = void 0;
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
var SamplingDecision;
(function (SamplingDecision) {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {}));
//# sourceMappingURL=Sampler.js.map
{"version":3,"file":"Sampler.js","sourceRoot":"","sources":["../../src/Sampler.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAUH;;;GAGG;AACH,IAAY,gBAgBX;AAhBD,WAAY,gBAAgB;IAC1B;;;OAGG;IACH,mEAAU,CAAA;IACV;;;OAGG;IACH,2DAAM,CAAA;IACN;;;OAGG;IACH,mFAAkB,CAAA;AACpB,CAAC,EAhBW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAgB3B","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples no traces. */
export declare class AlwaysOffSampler implements Sampler {
shouldSample(): SamplingResult;
toString(): string;
}
//# sourceMappingURL=AlwaysOffSampler.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlwaysOffSampler = void 0;
const Sampler_1 = require("../Sampler");
/** Sampler that samples no traces. */
class AlwaysOffSampler {
shouldSample() {
return {
decision: Sampler_1.SamplingDecision.NOT_RECORD,
};
}
toString() {
return 'AlwaysOffSampler';
}
}
exports.AlwaysOffSampler = AlwaysOffSampler;
//# sourceMappingURL=AlwaysOffSampler.js.map
{"version":3,"file":"AlwaysOffSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysOffSampler.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,wCAA8C;AAE9C,sCAAsC;AACtC,MAAa,gBAAgB;IAC3B,YAAY;QACV,OAAO;YACL,QAAQ,EAAE,0BAAgB,CAAC,UAAU;SACtC,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CACF;AAVD,4CAUC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples all traces. */
export declare class AlwaysOnSampler implements Sampler {
shouldSample(): SamplingResult;
toString(): string;
}
//# sourceMappingURL=AlwaysOnSampler.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlwaysOnSampler = void 0;
const Sampler_1 = require("../Sampler");
/** Sampler that samples all traces. */
class AlwaysOnSampler {
shouldSample() {
return {
decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED,
};
}
toString() {
return 'AlwaysOnSampler';
}
}
exports.AlwaysOnSampler = AlwaysOnSampler;
//# sourceMappingURL=AlwaysOnSampler.js.map
{"version":3,"file":"AlwaysOnSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysOnSampler.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,wCAA8C;AAE9C,uCAAuC;AACvC,MAAa,eAAe;IAC1B,YAAY;QACV,OAAO;YACL,QAAQ,EAAE,0BAAgB,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,iBAAiB,CAAC;IAC3B,CAAC;CACF;AAVD,0CAUC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n"]}
import type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';
import type { Sampler, SamplingResult } from '../Sampler';
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
export declare class ParentBasedSampler implements Sampler {
private _root;
private _remoteParentSampled;
private _remoteParentNotSampled;
private _localParentSampled;
private _localParentNotSampled;
constructor(config: ParentBasedSamplerConfig);
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: Attributes, links: Link[]): SamplingResult;
toString(): string;
}
interface ParentBasedSamplerConfig {
/** Sampler called for spans with no parent */
root: Sampler;
/** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */
remoteParentSampled?: Sampler;
/** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */
remoteParentNotSampled?: Sampler;
/** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */
localParentSampled?: Sampler;
/** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */
localParentNotSampled?: Sampler;
}
export {};
//# sourceMappingURL=ParentBasedSampler.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParentBasedSampler = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const AlwaysOffSampler_1 = require("./AlwaysOffSampler");
const AlwaysOnSampler_1 = require("./AlwaysOnSampler");
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
class ParentBasedSampler {
_root;
_remoteParentSampled;
_remoteParentNotSampled;
_localParentSampled;
_localParentNotSampled;
constructor(config) {
this._root = config.root;
if (!this._root) {
(0, core_1.globalErrorHandler)(new Error('ParentBasedSampler must have a root sampler configured'));
this._root = new AlwaysOnSampler_1.AlwaysOnSampler();
}
this._remoteParentSampled =
config.remoteParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler();
this._remoteParentNotSampled =
config.remoteParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler();
this._localParentSampled =
config.localParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler();
this._localParentNotSampled =
config.localParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler();
}
shouldSample(context, traceId, spanName, spanKind, attributes, links) {
const parentContext = api_1.trace.getSpanContext(context);
if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) {
return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.isRemote) {
if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {
return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {
return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
toString() {
return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
}
}
exports.ParentBasedSampler = ParentBasedSampler;
//# sourceMappingURL=ParentBasedSampler.js.map
{"version":3,"file":"ParentBasedSampler.js","sourceRoot":"","sources":["../../../src/sampler/ParentBasedSampler.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,4CAA2E;AAC3E,8CAAyD;AACzD,yDAAsD;AACtD,uDAAoD;AAGpD;;;GAGG;AACH,MAAa,kBAAkB;IACrB,KAAK,CAAU;IACf,oBAAoB,CAAU;IAC9B,uBAAuB,CAAU;IACjC,mBAAmB,CAAU;IAC7B,sBAAsB,CAAU;IAExC,YAAY,MAAgC;QAC1C,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC;QAEzB,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE;YACf,IAAA,yBAAkB,EAChB,IAAI,KAAK,CAAC,wDAAwD,CAAC,CACpE,CAAC;YACF,IAAI,CAAC,KAAK,GAAG,IAAI,iCAAe,EAAE,CAAC;SACpC;QAED,IAAI,CAAC,oBAAoB;YACvB,MAAM,CAAC,mBAAmB,IAAI,IAAI,iCAAe,EAAE,CAAC;QACtD,IAAI,CAAC,uBAAuB;YAC1B,MAAM,CAAC,sBAAsB,IAAI,IAAI,mCAAgB,EAAE,CAAC;QAC1D,IAAI,CAAC,mBAAmB;YACtB,MAAM,CAAC,kBAAkB,IAAI,IAAI,iCAAe,EAAE,CAAC;QACrD,IAAI,CAAC,sBAAs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BAA4B,IAAI,CAAC,uBAAuB,CAAC,QAAQ,EAAE,wBAAwB,IAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE,2BAA2B,IAAI,CAAC,sBAAsB,CAAC,QAAQ,EAAE,GAAG,CAAC;IAClT,CAAC;CACF;AA7FD,gDA6FC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n"]}
import type { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
export declare class TraceIdRatioBasedSampler implements Sampler {
private readonly _ratio;
private _upperBound;
constructor(ratio?: number);
shouldSample(context: unknown, traceId: string): SamplingResult;
toString(): string;
private _normalize;
private _accumulate;
}
//# sourceMappingURL=TraceIdRatioBasedSampler.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceIdRatioBasedSampler = void 0;
const api_1 = require("@opentelemetry/api");
const Sampler_1 = require("../Sampler");
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
class TraceIdRatioBasedSampler {
_ratio;
_upperBound;
constructor(ratio = 0) {
this._ratio = this._normalize(ratio);
this._upperBound = Math.floor(this._ratio * 0xffffffff);
}
shouldSample(context, traceId) {
return {
decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound
? Sampler_1.SamplingDecision.RECORD_AND_SAMPLED
: Sampler_1.SamplingDecision.NOT_RECORD,
};
}
toString() {
return `TraceIdRatioBased{${this._ratio}}`;
}
_normalize(ratio) {
if (typeof ratio !== 'number' || isNaN(ratio))
return 0;
return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
}
_accumulate(traceId) {
let accumulation = 0;
for (let i = 0; i < 32; i += 8) {
let part = 0;
for (let j = 0; j < 8; j++) {
const c = traceId.charCodeAt(i + j);
// Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15
const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;
part = (part << 4) | v;
}
accumulation = (accumulation ^ part) >>> 0;
}
return accumulation;
}
}
exports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler;
//# sourceMappingURL=TraceIdRatioBasedSampler.js.map
{"version":3,"file":"TraceIdRatioBasedSampler.js","sourceRoot":"","sources":["../../../src/sampler/TraceIdRatioBasedSampler.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4CAAoD;AAEpD,wCAA8C;AAE9C,2FAA2F;AAC3F,MAAa,wBAAwB;IAClB,MAAM,CAAC;IAChB,WAAW,CAAS;IAE5B,YAAY,KAAK,GAAG,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACrC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC;IAC1D,CAAC;IAED,YAAY,CAAC,OAAgB,EAAE,OAAe;QAC5C,O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AY,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;SAC5C;QACD,OAAO,YAAY,CAAC;IACtB,CAAC;CACF;AAzCD,4DAyCC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < 32; i += 8) {\n let part = 0;\n for (let j = 0; j < 8; j++) {\n const c = traceId.charCodeAt(i + j);\n // Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15\n const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;\n part = (part << 4) | v;\n }\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n"]}
/**
* Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const ATTR_OTEL_SPAN_PARENT_ORIGIN: "otel.span.parent.origin";
/**
* The result value of the sampler for this span
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const ATTR_OTEL_SPAN_SAMPLING_RESULT: "otel.span.sampling_result";
/**
* The number of created spans with `recording=true` for which the end operation has not been called yet.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const METRIC_OTEL_SDK_SPAN_LIVE: "otel.sdk.span.live";
/**
* The number of created spans.
*
* @note Implementations **MUST** record this metric for all spans, even for non-recording ones.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
export declare const METRIC_OTEL_SDK_SPAN_STARTED: "otel.sdk.span.started";
//# sourceMappingURL=semconv.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.METRIC_OTEL_SDK_SPAN_STARTED = exports.METRIC_OTEL_SDK_SPAN_LIVE = exports.ATTR_OTEL_SPAN_SAMPLING_RESULT = exports.ATTR_OTEL_SPAN_PARENT_ORIGIN = void 0;
/*
* This file contains a copy of unstable semantic convention definitions
* used by this package.
* @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv
*/
/**
* Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
exports.ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin';
/**
* The result value of the sampler for this span
*
* @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
exports.ATTR_OTEL_SPAN_SAMPLING_RESULT = 'otel.span.sampling_result';
/**
* The number of created spans with `recording=true` for which the end operation has not been called yet.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
exports.METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live';
/**
* The number of created spans.
*
* @note Implementations **MUST** record this metric for all spans, even for non-recording ones.
*
* @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
*/
exports.METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started';
//# sourceMappingURL=semconv.js.map
{"version":3,"file":"semconv.js","sourceRoot":"","sources":["../../src/semconv.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH;;;;GAIG;AAEH;;;;GAIG;AACU,QAAA,4BAA4B,GAAG,yBAAkC,CAAC;AAE/E;;;;GAIG;AACU,QAAA,8BAA8B,GACzC,2BAAoC,CAAC;AAEvC;;;;GAIG;AACU,QAAA,yBAAyB,GAAG,oBAA6B,CAAC;AAEvE;;;;;;GAMG;AACU,QAAA,4BAA4B,GAAG,uBAAgC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n 'otel.span.sampling_result' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n"]}
import type { Context, Exception, HrTime, Link, Span as APISpan, SpanOptions as APISpanOptions, Attributes, AttributeValue, SpanContext, SpanKind, SpanStatus, TimeInput } from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { Resource } from '@opentelemetry/resources';
import type { ReadableSpan } from './export/ReadableSpan';
import type { SpanProcessor } from './SpanProcessor';
import type { TimedEvent } from './TimedEvent';
import type { SpanLimits } from './types';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
/**
* This type provides the properties of @link{ReadableSpan} at the same time
* of the Span API
*/
export type Span = APISpan & ReadableSpan;
type SpanOptions = Omit<APISpanOptions, 'root'> & {
resource: Resource;
scope: InstrumentationScope;
context: Context;
spanContext: SpanContext;
name: string;
kind: SpanKind;
parentSpanContext?: SpanContext;
spanLimits: SpanLimits;
spanProcessor: SpanProcessor;
recordEndMetrics?: () => void;
};
/**
* This class represents a span.
*/
export declare class SpanImpl implements Span {
private readonly _spanContext;
readonly kind: SpanKind;
readonly parentSpanContext?: SpanContext;
readonly attributes: Attributes;
readonly links: Link[];
readonly events: TimedEvent[];
readonly startTime: HrTime;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
private _droppedAttributesCount;
private _droppedEventsCount;
private _droppedLinksCount;
private _attributesCount;
name: string;
status: SpanStatus;
endTime: HrTime;
private _ended;
private _duration;
private readonly _spanProcessor;
private readonly _spanLimits;
private readonly _attributeValueLengthLimit;
private readonly _recordEndMetrics?;
private readonly _performanceStartTime;
private readonly _performanceOffset;
private readonly _startTimeProvided;
/**
* Constructs a new SpanImpl instance.
*/
constructor(opts: SpanOptions);
spanContext(): SpanContext;
setAttribute(key: string, value?: AttributeValue): this;
setAttributes(attributes: Attributes): this;
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name: string, attributesOrStartTime?: Attributes | TimeInput, timeStamp?: TimeInput): this;
addLink(link: Link): this;
addLinks(links: Link[]): this;
setStatus(status: SpanStatus): this;
updateName(name: string): this;
end(endTime?: TimeInput): void;
private _getTime;
isRecording(): boolean;
recordException(exception: Exception, time?: TimeInput): void;
get duration(): HrTime;
get ended(): boolean;
get droppedAttributesCount(): number;
get droppedEventsCount(): number;
get droppedLinksCount(): number;
private _isSpanEnded;
private _truncateToLimitUtil;
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
private _truncateToSize;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
export {};
//# sourceMappingURL=Span.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpanImpl = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
const enums_1 = require("./enums");
const inspect_1 = require("./inspect");
/**
* This class represents a span.
*/
class SpanImpl {
// Below properties are included to implement ReadableSpan for export
// purposes but are not intended to be written-to directly.
_spanContext;
kind;
parentSpanContext;
attributes = {};
links = [];
events = [];
startTime;
resource;
instrumentationScope;
_droppedAttributesCount = 0;
_droppedEventsCount = 0;
_droppedLinksCount = 0;
_attributesCount = 0;
name;
status = {
code: api_1.SpanStatusCode.UNSET,
};
endTime = [0, 0];
_ended = false;
_duration = [-1, -1];
_spanProcessor;
_spanLimits;
_attributeValueLengthLimit;
_recordEndMetrics;
_performanceStartTime;
_performanceOffset;
_startTimeProvided;
/**
* Constructs a new SpanImpl instance.
*/
constructor(opts) {
const now = Date.now();
this._spanContext = opts.spanContext;
this._performanceStartTime = core_1.otperformance.now();
this._performanceOffset =
now - (this._performanceStartTime + core_1.otperformance.timeOrigin);
this._startTimeProvided = opts.startTime != null;
this._spanLimits = opts.spanLimits;
this._attributeValueLengthLimit =
this._spanLimits.attributeValueLengthLimit ?? 0;
this._spanProcessor = opts.spanProcessor;
this.name = opts.name;
this.parentSpanContext = opts.parentSpanContext;
this.kind = opts.kind;
if (opts.links) {
for (const link of opts.links) {
this.addLink(link);
}
}
this.startTime = this._getTime(opts.startTime ?? now);
this.resource = opts.resource;
this.instrumentationScope = opts.scope;
this._recordEndMetrics = opts.recordEndMetrics;
if (opts.attributes != null) {
this.setAttributes(opts.attributes);
}
this._spanProcessor.onStart(this, opts.context);
}
spanContext() {
return this._spanContext;
}
setAttribute(key, value) {
if (value == null || this._isSpanEnded())
return this;
if (key.length === 0) {
api_1.diag.warn(`Invalid attribute key: ${key}`);
return this;
}
if (!(0, core_1.isAttributeValue)(value)) {
api_1.diag.warn(`Invalid attribute value set for key: ${key}`);
return this;
}
const { attributeCountLimit } = this._spanLimits;
const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
if (attributeCountLimit !== undefined &&
this._attributesCount >= attributeCountLimit &&
isNewKey) {
this._droppedAttributesCount++;
return this;
}
this.attributes[key] = this._truncateToSize(value);
if (isNewKey) {
this._attributesCount++;
}
return this;
}
setAttributes(attributes) {
for (const key in attributes) {
if (Object.prototype.hasOwnProperty.call(attributes, key)) {
this.setAttribute(key, attributes[key]);
}
}
return this;
}
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name, attributesOrStartTime, timeStamp) {
if (this._isSpanEnded())
return this;
const { eventCountLimit } = this._spanLimits;
if (eventCountLimit === 0) {
api_1.diag.warn('No events allowed.');
this._droppedEventsCount++;
return this;
}
if (eventCountLimit !== undefined &&
this.events.length >= eventCountLimit) {
if (this._droppedEventsCount === 0) {
api_1.diag.debug('Dropping extra events.');
}
this.events.shift();
this._droppedEventsCount++;
}
if ((0, core_1.isTimeInput)(attributesOrStartTime)) {
if (!(0, core_1.isTimeInput)(timeStamp)) {
timeStamp = attributesOrStartTime;
}
attributesOrStartTime = undefined;
}
const sanitized = (0, core_1.sanitizeAttributes)(attributesOrStartTime);
const { attributePerEventCountLimit } = this._spanLimits;
const attributes = {};
let droppedAttributesCount = 0;
let eventAttributesCount = 0;
for (const attr in sanitized) {
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
continue;
}
const attrVal = sanitized[attr];
if (attributePerEventCountLimit !== undefined &&
eventAttributesCount >= attributePerEventCountLimit) {
droppedAttributesCount++;
continue;
}
attributes[attr] = this._truncateToSize(attrVal);
eventAttributesCount++;
}
this.events.push({
name,
attributes,
time: this._getTime(timeStamp),
droppedAttributesCount,
});
return this;
}
addLink(link) {
if (this._isSpanEnded())
return this;
const { linkCountLimit } = this._spanLimits;
if (linkCountLimit === 0) {
this._droppedLinksCount++;
return this;
}
if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {
if (this._droppedLinksCount === 0) {
api_1.diag.debug('Dropping extra links.');
}
this.links.shift();
this._droppedLinksCount++;
}
const { attributePerLinkCountLimit } = this._spanLimits;
const sanitized = (0, core_1.sanitizeAttributes)(link.attributes);
const attributes = {};
let droppedAttributesCount = 0;
let linkAttributesCount = 0;
for (const attr in sanitized) {
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
continue;
}
const attrVal = sanitized[attr];
if (attributePerLinkCountLimit !== undefined &&
linkAttributesCount >= attributePerLinkCountLimit) {
droppedAttributesCount++;
continue;
}
attributes[attr] = this._truncateToSize(attrVal);
linkAttributesCount++;
}
const processedLink = { context: link.context };
if (linkAttributesCount > 0) {
processedLink.attributes = attributes;
}
if (droppedAttributesCount > 0) {
processedLink.droppedAttributesCount = droppedAttributesCount;
}
this.links.push(processedLink);
return this;
}
addLinks(links) {
for (const link of links) {
this.addLink(link);
}
return this;
}
setStatus(status) {
if (this._isSpanEnded())
return this;
if (status.code === api_1.SpanStatusCode.UNSET)
return this;
if (this.status.code === api_1.SpanStatusCode.OK)
return this;
const newStatus = { code: status.code };
// When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`,
// TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()
// as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or
// undefined to avoid an incorrect type causing issues downstream.
if (status.code === api_1.SpanStatusCode.ERROR) {
if (typeof status.message === 'string') {
newStatus.message = status.message;
}
else if (status.message != null) {
api_1.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
}
}
this.status = newStatus;
return this;
}
updateName(name) {
if (this._isSpanEnded())
return this;
this.name = name;
return this;
}
end(endTime) {
if (this._isSpanEnded()) {
api_1.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
return;
}
this.endTime = this._getTime(endTime);
this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime);
if (this._duration[0] < 0) {
api_1.diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime);
this.endTime = this.startTime.slice();
this._duration = [0, 0];
}
if (this._droppedEventsCount > 0) {
api_1.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
}
if (this._droppedLinksCount > 0) {
api_1.diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);
}
if (this._spanProcessor.onEnding) {
this._spanProcessor.onEnding(this);
}
this._recordEndMetrics?.();
this._ended = true;
this._spanProcessor.onEnd(this);
}
_getTime(inp) {
if (typeof inp === 'number' && inp <= core_1.otperformance.now()) {
// must be a performance timestamp
// apply correction and convert to hrtime
return (0, core_1.hrTime)(inp + this._performanceOffset);
}
if (typeof inp === 'number') {
return (0, core_1.millisToHrTime)(inp);
}
if (inp instanceof Date) {
return (0, core_1.millisToHrTime)(inp.getTime());
}
if ((0, core_1.isTimeInputHrTime)(inp)) {
return inp;
}
if (this._startTimeProvided) {
// if user provided a time for the start manually
// we can't use duration to calculate event/end times
return (0, core_1.millisToHrTime)(Date.now());
}
const msDuration = core_1.otperformance.now() - this._performanceStartTime;
return (0, core_1.addHrTimes)(this.startTime, (0, core_1.millisToHrTime)(msDuration));
}
isRecording() {
return this._ended === false;
}
recordException(exception, time) {
const attributes = {};
if (typeof exception === 'string') {
attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception;
}
else if (exception) {
if (exception.code) {
attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.code.toString();
}
else if (exception.name) {
attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.name;
}
if (exception.message) {
attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception.message;
}
if (exception.stack) {
attributes[semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE] = exception.stack;
}
}
// these are minimum requirements from spec
if (attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] || attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE]) {
this.addEvent(enums_1.ExceptionEventName, attributes, time);
}
else {
api_1.diag.warn(`Failed to record an exception ${exception}`);
}
}
get duration() {
return this._duration;
}
get ended() {
return this._ended;
}
get droppedAttributesCount() {
return this._droppedAttributesCount;
}
get droppedEventsCount() {
return this._droppedEventsCount;
}
get droppedLinksCount() {
return this._droppedLinksCount;
}
_isSpanEnded() {
if (this._ended) {
const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
api_1.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
}
return this._ended;
}
// Utility function to truncate given value within size
// for value type of string, will truncate to given limit
// for type of non-string, will return same value
_truncateToLimitUtil(value, limit) {
if (value.length <= limit) {
return value;
}
return value.substring(0, limit);
}
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
_truncateToSize(value) {
const limit = this._attributeValueLengthLimit;
// Check limit
if (limit <= 0) {
// Negative values are invalid, so do not truncate
api_1.diag.warn(`Attribute value limit must be positive, got ${limit}`);
return value;
}
// String
if (typeof value === 'string') {
return this._truncateToLimitUtil(value, limit);
}
// Array of strings
if (Array.isArray(value)) {
return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val);
}
// Other types, no need to apply value length limit
return value;
}
[inspect_1.inspectCustom](depth, options, inspect) {
const payload = {
name: this.name,
kind: this.kind,
spanContext: this._spanContext,
parentSpanContext: this.parentSpanContext,
status: this.status,
startTime: this.startTime,
endTime: this.endTime,
duration: this._duration,
ended: this._ended,
attributes: this.attributes,
events: this.events,
links: this.links,
droppedAttributesCount: this._droppedAttributesCount,
droppedEventsCount: this._droppedEventsCount,
droppedLinksCount: this._droppedLinksCount,
instrumentationScope: this.instrumentationScope,
resource: { attributes: (0, inspect_1.settledResourceAttributes)(this.resource) },
};
return (0, inspect_1.formatInspect)('SpanImpl', payload, depth, options, inspect);
}
}
exports.SpanImpl = SpanImpl;
//# sourceMappingURL=Span.js.map
{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAgBH,4CAA0D;AAE1D,8CAU6B;AAE7B,8EAI6C;AAE7C,mCAA6C;AAK7C,uCAImB;AAyBnB;;GAEG;AACH,MAAa,QAAQ;IACnB,qEAA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AAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CACtE,CAAC;SACH;QAED,mDAAmD;QACnD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,CAAC,uBAAa,CAAC,CACb,KAAa,EACb,OAA0C,EAC1C,OAA8B;QAE9B,MAAM,OAAO,GAAG;YACd,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,YAAY;YAC9B,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,KAAK,EAAE,IAAI,CAAC,MAAM;YAClB,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,sBAAsB,EAAE,IAAI,CAAC,uBAAuB;YACpD,kBAAkB,EAAE,IAAI,CAAC,mBAAmB;YAC5C,iBAAiB,EAAE,IAAI,CAAC,kBAAkB;YAC1C,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,QAAQ,EAAE,EAAE,UAAU,EAAE,IAAA,mCAAyB,EAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;SACnE,CAAC;QACF,OAAO,IAAA,uBAAa,EAAC,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACrE,CAAC;CACF;AAneD,4BAmeC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanOptions as APISpanOptions,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n // Required here to override optional `kind` from the API's SpanOptions\n // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n private readonly _recordEndMetrics?: () => void;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit ?? 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n eventAttributesCount++;\n }\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n\n addLink(link: Link): this {\n if (this._isSpanEnded()) return this;\n\n const { linkCountLimit } = this._spanLimits;\n\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n linkAttributesCount++;\n }\n\n const processedLink: Link = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n\n this.links.push(processedLink);\n return this;\n }\n\n addLinks(links: Link[]): this {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n if (status.code === SpanStatusCode.UNSET) return this;\n if (this.status.code === SpanStatusCode.OK) return this;\n\n const newStatus: SpanStatus = { code: status.code };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n } else if (status.message != null) {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n }\n }\n\n this.status = newStatus;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(\n `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const payload = {\n name: this.name,\n kind: this.kind,\n spanContext: this._spanContext,\n parentSpanContext: this.parentSpanContext,\n status: this.status,\n startTime: this.startTime,\n endTime: this.endTime,\n duration: this._duration,\n ended: this._ended,\n attributes: this.attributes,\n events: this.events,\n links: this.links,\n droppedAttributesCount: this._droppedAttributesCount,\n droppedEventsCount: this._droppedEventsCount,\n droppedLinksCount: this._droppedLinksCount,\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this.resource) },\n };\n return formatInspect('SpanImpl', payload, depth, options, inspect);\n }\n}\n"]}
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './export/ReadableSpan';
import type { Span } from './Span';
/**
* SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks
* for when a {@link Span} is started or when a {@link Span} is ended.
*/
export interface SpanProcessor {
/**
* Forces to export all finished spans
*/
forceFlush(): Promise<void>;
/**
* Called when a {@link Span} is started, if the `span.isRecording()`
* returns true.
* @param span the Span that just started.
*/
onStart(span: Span, parentContext: Context): void;
/**
* Called when a {@link Span} is ending, if the `span.isRecording()`
* returns true.
* @param span the Span that is ending.
*
* @experimental This method is experimental and may break in minor versions of this package
*/
onEnding?(span: Span): void;
/**
* Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`
* returns true.
* @param span the Span that just ended.
*/
onEnd(span: ReadableSpan): void;
/**
* Shuts down the processor. Called when SDK is shut down. This is an
* opportunity for processor to do any cleanup required.
*/
shutdown(): Promise<void>;
}
//# sourceMappingURL=SpanProcessor.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=SpanProcessor.js.map
{"version":3,"file":"SpanProcessor.js","sourceRoot":"","sources":["../../src/SpanProcessor.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\n\n/**\n * SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks\n * for when a {@link Span} is started or when a {@link Span} is ended.\n */\nexport interface SpanProcessor {\n /**\n * Forces to export all finished spans\n */\n forceFlush(): Promise<void>;\n\n /**\n * Called when a {@link Span} is started, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just started.\n */\n onStart(span: Span, parentContext: Context): void;\n\n /**\n * Called when a {@link Span} is ending, if the `span.isRecording()`\n * returns true.\n * @param span the Span that is ending.\n *\n * @experimental This method is experimental and may break in minor versions of this package\n */\n onEnding?(span: Span): void;\n\n /**\n * Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just ended.\n */\n onEnd(span: ReadableSpan): void;\n\n /**\n * Shuts down the processor. Called when SDK is shut down. This is an\n * opportunity for processor to do any cleanup required.\n */\n shutdown(): Promise<void>;\n}\n"]}
import type { HrTime, Attributes } from '@opentelemetry/api';
/**
* Represents a timed event.
* A timed event is an event with a timestamp.
*/
export interface TimedEvent {
time: HrTime;
/** The name of the event. */
name: string;
/** The attributes of the event. */
attributes?: Attributes;
/** Count of attributes of the event that were dropped due to collection limits */
droppedAttributesCount?: number;
}
//# sourceMappingURL=TimedEvent.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=TimedEvent.js.map
{"version":3,"file":"TimedEvent.js","sourceRoot":"","sources":["../../src/TimedEvent.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime, Attributes } from '@opentelemetry/api';\n\n/**\n * Represents a timed event.\n * A timed event is an event with a timestamp.\n */\nexport interface TimedEvent {\n time: HrTime;\n /** The name of the event. */\n name: string;\n /** The attributes of the event. */\n attributes?: Attributes;\n /** Count of attributes of the event that were dropped due to collection limits */\n droppedAttributesCount?: number;\n}\n"]}
import * as api from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { GeneralLimits, SpanLimits, TracerConfig } from './types';
import type { SpanProcessor } from './SpanProcessor';
import type { Resource } from '@opentelemetry/resources';
import type { InspectFn, InspectStylizeOptions } from './inspect';
import { inspectCustom } from './inspect';
/**
* This class represents a basic tracer.
*/
export declare class Tracer implements api.Tracer {
private readonly _sampler;
private readonly _generalLimits;
private readonly _spanLimits;
private readonly _idGenerator;
readonly instrumentationScope: InstrumentationScope;
private readonly _resource;
private readonly _spanProcessor;
private readonly _tracerMetrics;
/**
* Constructs a new Tracer instance.
*/
constructor(instrumentationScope: InstrumentationScope, config: TracerConfig, resource: Resource, spanProcessor: SpanProcessor);
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
startSpan(name: string, options?: api.SpanOptions, context?: api.Context): api.Span;
/**
* Starts a new {@link Span} and calls the given function passing it the
* created span as first argument.
* Additionally the new span gets set in context and this context is activated
* for the duration of the function call.
*
* **Important**: The callback function is responsible for calling `span.end()`
* to finish the span. Unlike some other OpenTelemetry implementations, the span
* is NOT automatically ended when the callback returns. If `span.end()` is not
* called, the span will never be exported and will be silently lost.
*
* @param name The name of the span
* @param [options] SpanOptions used for span creation
* @param [context] Context to use to extract parent
* @param fn function called in the context of the span and receives the newly created span as an argument
* @returns return value of fn
* @example
* const something = tracer.startActiveSpan('op', span => {
* try {
* do some work
* span.setStatus({code: SpanStatusCode.OK});
* return something;
* } catch (err) {
* span.setStatus({
* code: SpanStatusCode.ERROR,
* message: err.message,
* });
* throw err;
* } finally {
* span.end();
* }
* });
* @example
* const span = tracer.startActiveSpan('op', span => {
* try {
* do some work
* return span;
* } catch (err) {
* span.setStatus({
* code: SpanStatusCode.ERROR,
* message: err.message,
* });
* throw err;
* }
* });
* do some more work
* span.end();
*/
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, fn: F): ReturnType<F>;
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, opts: api.SpanOptions, fn: F): ReturnType<F>;
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, opts: api.SpanOptions, ctx: api.Context, fn: F): ReturnType<F>;
/** Returns the active {@link GeneralLimits}. */
getGeneralLimits(): GeneralLimits;
/** Returns the active {@link SpanLimits}. */
getSpanLimits(): SpanLimits;
[inspectCustom](depth: number, options: InspectStylizeOptions | undefined, inspect: InspectFn | undefined): unknown;
}
//# sourceMappingURL=Tracer.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tracer = void 0;
const api = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const Span_1 = require("./Span");
const utility_1 = require("./utility");
const platform_1 = require("./platform");
const TracerMetrics_1 = require("./TracerMetrics");
const version_1 = require("./version");
const inspect_1 = require("./inspect");
/**
* This class represents a basic tracer.
*/
class Tracer {
_sampler;
_generalLimits;
_spanLimits;
_idGenerator;
instrumentationScope;
_resource;
_spanProcessor;
_tracerMetrics;
/**
* Constructs a new Tracer instance.
*/
constructor(instrumentationScope, config, resource, spanProcessor) {
const localConfig = (0, utility_1.mergeConfig)(config);
this._sampler = localConfig.sampler;
this._generalLimits = localConfig.generalLimits;
this._spanLimits = localConfig.spanLimits;
this._idGenerator = config.idGenerator || new platform_1.RandomIdGenerator();
this._resource = resource;
this._spanProcessor = spanProcessor;
this.instrumentationScope = instrumentationScope;
const meter = localConfig.meterProvider
? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', version_1.VERSION)
: api.createNoopMeter();
this._tracerMetrics = new TracerMetrics_1.TracerMetrics(meter);
}
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
startSpan(name, options = {}, context = api.context.active()) {
// remove span from context in case a root span is requested via options
if (options.root) {
context = api.trace.deleteSpan(context);
}
const parentSpan = api.trace.getSpan(context);
if ((0, core_1.isTracingSuppressed)(context)) {
api.diag.debug('Instrumentation suppressed, returning Noop Span');
const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);
return nonRecordingSpan;
}
const parentSpanContext = parentSpan?.spanContext();
const spanId = this._idGenerator.generateSpanId();
let validParentSpanContext;
let traceId;
let traceState;
if (!parentSpanContext ||
!api.trace.isSpanContextValid(parentSpanContext)) {
// New root span.
traceId = this._idGenerator.generateTraceId();
}
else {
// New child span.
traceId = parentSpanContext.traceId;
traceState = parentSpanContext.traceState;
validParentSpanContext = parentSpanContext;
}
const spanKind = options.kind ?? api.SpanKind.INTERNAL;
const links = (options.links ?? []).map(link => {
return {
context: link.context,
attributes: (0, core_1.sanitizeAttributes)(link.attributes),
};
});
const attributes = (0, core_1.sanitizeAttributes)(options.attributes);
// make sampling decision
const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links);
const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision);
traceState = samplingResult.traceState ?? traceState;
const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED
? api.TraceFlags.SAMPLED
: api.TraceFlags.NONE;
const spanContext = { traceId, spanId, traceFlags, traceState };
if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {
api.diag.debug('Recording is off, propagating context in a non-recording span');
const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);
return nonRecordingSpan;
}
// Set initial span attributes. The attributes object may have been mutated
// by the sampler, so we sanitize the merged attributes before setting them.
const initAttributes = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes));
const span = new Span_1.SpanImpl({
resource: this._resource,
scope: this.instrumentationScope,
context,
spanContext,
name,
kind: spanKind,
links,
parentSpanContext: validParentSpanContext,
attributes: initAttributes,
startTime: options.startTime,
spanProcessor: this._spanProcessor,
spanLimits: this._spanLimits,
recordEndMetrics,
});
return span;
}
startActiveSpan(name, arg2, arg3, arg4) {
let opts;
let ctx;
let fn;
if (arguments.length < 2) {
return;
}
else if (arguments.length === 2) {
fn = arg2;
}
else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
}
else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
const parentContext = ctx ?? api.context.active();
const span = this.startSpan(name, opts, parentContext);
const contextWithSpanSet = api.trace.setSpan(parentContext, span);
return api.context.with(contextWithSpanSet, fn, undefined, span);
}
/** Returns the active {@link GeneralLimits}. */
getGeneralLimits() {
return this._generalLimits;
}
/** Returns the active {@link SpanLimits}. */
getSpanLimits() {
return this._spanLimits;
}
[inspect_1.inspectCustom](depth, options, inspect) {
const payload = {
instrumentationScope: this.instrumentationScope,
resource: { attributes: (0, inspect_1.settledResourceAttributes)(this._resource) },
spanLimits: this._spanLimits,
generalLimits: this._generalLimits,
};
return (0, inspect_1.formatInspect)('Tracer', payload, depth, options, inspect);
}
}
exports.Tracer = Tracer;
//# sourceMappingURL=Tracer.js.map
{"version":3,"file":"Tracer.js","sourceRoot":"","sources":["../../src/Tracer.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,0CAA0C;AAE1C,8CAA8E;AAC9E,iCAAkC;AAElC,uCAAwC;AAIxC,yCAA+C;AAE/C,mDAAgD;AAChD,uCAAoC;AAEpC,uCAImB;AAEnB;;GAEG;AACH,MAAa,MAAM;IACA,QAAQ,CAAU;IAClB,cAAc,CAAgB;IAC9B,WAAW,CAAa;IACxB,YAAY,CAAc;IAClC,oBAAoB,CAAuB;IAEnC,SAAS,CAAW;IACpB,cAAc,CAA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AAC,EAAE;YACnE,UAAU,EAAE,IAAI,CAAC,WAAW;YAC5B,aAAa,EAAE,IAAI,CAAC,cAAc;SACnC,CAAC;QACF,OAAO,IAAA,uBAAa,EAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACnE,CAAC;CACF;AA9PD,wBA8PC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n private readonly _tracerMetrics: TracerMetrics;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n\n const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\n this._tracerMetrics = new TracerMetrics(meter);\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n const recordEndMetrics = this._tracerMetrics.startSpan(\n parentSpanContext,\n samplingResult.decision\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n recordEndMetrics,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * **Important**: The callback function is responsible for calling `span.end()`\n * to finish the span. Unlike some other OpenTelemetry implementations, the span\n * is NOT automatically ended when the callback returns. If `span.end()` is not\n * called, the span will never be exported and will be silently lost.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const payload = {\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this._resource) },\n spanLimits: this._spanLimits,\n generalLimits: this._generalLimits,\n };\n return formatInspect('Tracer', payload, depth, options, inspect);\n }\n}\n"]}
import type { Meter, SpanContext } from '@opentelemetry/api';
import { SamplingDecision } from './Sampler';
/**
* Generates `otel.sdk.span.*` metrics.
* https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
*/
export declare class TracerMetrics {
private readonly startedSpans;
private readonly liveSpans;
constructor(meter: Meter);
startSpan(parentSpanCtx: SpanContext | undefined, samplingDecision: SamplingDecision): () => void;
}
//# sourceMappingURL=TracerMetrics.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TracerMetrics = void 0;
const Sampler_1 = require("./Sampler");
const semconv_1 = require("./semconv");
/**
* Generates `otel.sdk.span.*` metrics.
* https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
*/
class TracerMetrics {
startedSpans;
liveSpans;
constructor(meter) {
this.startedSpans = meter.createCounter(semconv_1.METRIC_OTEL_SDK_SPAN_STARTED, {
unit: '{span}',
description: 'The number of created spans.',
});
this.liveSpans = meter.createUpDownCounter(semconv_1.METRIC_OTEL_SDK_SPAN_LIVE, {
unit: '{span}',
description: 'The number of currently live spans.',
});
}
startSpan(parentSpanCtx, samplingDecision) {
const samplingDecisionStr = samplingDecisionToString(samplingDecision);
this.startedSpans.add(1, {
[semconv_1.ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),
[semconv_1.ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,
});
if (samplingDecision === Sampler_1.SamplingDecision.NOT_RECORD) {
return () => { };
}
const liveSpanAttributes = {
[semconv_1.ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,
};
this.liveSpans.add(1, liveSpanAttributes);
return () => {
this.liveSpans.add(-1, liveSpanAttributes);
};
}
}
exports.TracerMetrics = TracerMetrics;
function parentOrigin(parentSpanContext) {
if (!parentSpanContext) {
return 'none';
}
if (parentSpanContext.isRemote) {
return 'remote';
}
return 'local';
}
function samplingDecisionToString(decision) {
switch (decision) {
case Sampler_1.SamplingDecision.RECORD_AND_SAMPLED:
return 'RECORD_AND_SAMPLE';
case Sampler_1.SamplingDecision.RECORD:
return 'RECORD_ONLY';
case Sampler_1.SamplingDecision.NOT_RECORD:
return 'DROP';
}
}
//# sourceMappingURL=TracerMetrics.js.map
{"version":3,"file":"TracerMetrics.js","sourceRoot":"","sources":["../../src/TracerMetrics.ts"],"names":[],"mappings":";;;AAUA,uCAA6C;AAC7C,uCAKmB;AAEnB;;;GAGG;AACH,MAAa,aAAa;IACP,YAA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,CAAC,QAA0B;IAC1D,QAAQ,QAAQ,EAAE;QAChB,KAAK,0BAAgB,CAAC,kBAAkB;YACtC,OAAO,mBAAmB,CAAC;QAC7B,KAAK,0BAAgB,CAAC,MAAM;YAC1B,OAAO,aAAa,CAAC;QACvB,KAAK,0BAAgB,CAAC,UAAU;YAC9B,OAAO,MAAM,CAAC;KACjB;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Counter,\n Meter,\n SpanContext,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n ATTR_OTEL_SPAN_PARENT_ORIGIN,\n ATTR_OTEL_SPAN_SAMPLING_RESULT,\n METRIC_OTEL_SDK_SPAN_LIVE,\n METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n private readonly startedSpans: Counter;\n private readonly liveSpans: UpDownCounter;\n\n constructor(meter: Meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n\n startSpan(\n parentSpanCtx: SpanContext | undefined,\n samplingDecision: SamplingDecision\n ): () => void {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => {};\n }\n\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n"]}
import type { ContextManager, MeterProvider, TextMapPropagator } from '@opentelemetry/api';
import type { Resource } from '@opentelemetry/resources';
import type { IdGenerator } from './IdGenerator';
import type { Sampler } from './Sampler';
import type { SpanProcessor } from './SpanProcessor';
/**
* TracerConfig provides an interface for configuring a Basic Tracer.
*/
export interface TracerConfig {
/**
* Sampler determines if a span should be recorded or should be a NoopSpan.
*/
sampler?: Sampler;
/** General Limits */
generalLimits?: GeneralLimits;
/** Span Limits */
spanLimits?: SpanLimits;
/** Resource associated with trace telemetry */
resource?: Resource;
/**
* Generator of trace and span IDs
* The default idGenerator generates random ids
*/
idGenerator?: IdGenerator;
/**
* How long the forceFlush can run before it is cancelled.
* The default value is 30000ms
*/
forceFlushTimeoutMillis?: number;
/**
* List of SpanProcessor for the tracer
*/
spanProcessors?: SpanProcessor[];
/**
* A meter provider to record trace SDK metrics to.
* @experimental This option is experimental and is subject to breaking changes in minor releases.
*/
meterProvider?: MeterProvider;
}
/**
* Configuration options for registering the API with the SDK.
* Undefined values may be substituted for defaults, and null
* values will not be registered.
*/
export interface SDKRegistrationConfig {
/** Propagator to register as the global propagator */
propagator?: TextMapPropagator | null;
/** Context manager to register as the global context manager */
contextManager?: ContextManager | null;
}
/** Global configuration limits of trace service */
export interface GeneralLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per trace */
attributeCountLimit?: number;
}
/** Global configuration of trace service */
export interface SpanLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per span */
attributeCountLimit?: number;
/** linkCountLimit is number of links per span */
linkCountLimit?: number;
/** eventCountLimit is number of message events per span */
eventCountLimit?: number;
/** attributePerEventCountLimit is the maximum number of attributes allowed per span event */
attributePerEventCountLimit?: number;
/** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */
attributePerLinkCountLimit?: number;
}
/** Interface configuration for a buffer. */
export interface BufferConfig {
/** The maximum batch size of every export. It must be smaller or equal to
* maxQueueSize. The default value is 512. */
maxExportBatchSize?: number;
/** The delay interval in milliseconds between two consecutive exports.
* The default value is 5000ms. */
scheduledDelayMillis?: number;
/** How long the export can run before it is cancelled.
* The default value is 30000ms */
exportTimeoutMillis?: number;
/** The maximum queue size. After the size is reached spans are dropped.
* The default value is 2048. */
maxQueueSize?: number;
}
/** Interface configuration for BatchSpanProcessor on browser */
export interface BatchSpanProcessorBrowserConfig extends BufferConfig {
/** Disable flush when a user navigates to a new page, closes the tab or the browser, or,
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}
//# sourceMappingURL=types.d.ts.map
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n ContextManager,\n MeterProvider,\n TextMapPropagator,\n} from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { IdGenerator } from './IdGenerator';\nimport type { Sampler } from './Sampler';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * TracerConfig provides an interface for configuring a Basic Tracer.\n */\nexport interface TracerConfig {\n /**\n * Sampler determines if a span should be recorded or should be a NoopSpan.\n */\n sampler?: Sampler;\n\n /** General Limits */\n generalLimits?: GeneralLimits;\n\n /** Span Limits */\n spanLimits?: SpanLimits;\n\n /** Resource associated with trace telemetry */\n resource?: Resource;\n\n /**\n * Generator of trace and span IDs\n * The default idGenerator generates random ids\n */\n idGenerator?: IdGenerator;\n\n /**\n * How long the forceFlush can run before it is cancelled.\n * The default value is 30000ms\n */\n forceFlushTimeoutMillis?: number;\n\n /**\n * List of SpanProcessor for the tracer\n */\n spanProcessors?: SpanProcessor[];\n\n /**\n * A meter provider to record trace SDK metrics to.\n * @experimental This option is experimental and is subject to breaking changes in minor releases.\n */\n meterProvider?: MeterProvider;\n}\n\n/**\n * Configuration options for registering the API with the SDK.\n * Undefined values may be substituted for defaults, and null\n * values will not be registered.\n */\nexport interface SDKRegistrationConfig {\n /** Propagator to register as the global propagator */\n propagator?: TextMapPropagator | null;\n\n /** Context manager to register as the global context manager */\n contextManager?: ContextManager | null;\n}\n\n/** Global configuration limits of trace service */\nexport interface GeneralLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per trace */\n attributeCountLimit?: number;\n}\n\n/** Global configuration of trace service */\nexport interface SpanLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per span */\n attributeCountLimit?: number;\n /** linkCountLimit is number of links per span */\n linkCountLimit?: number;\n /** eventCountLimit is number of message events per span */\n eventCountLimit?: number;\n /** attributePerEventCountLimit is the maximum number of attributes allowed per span event */\n attributePerEventCountLimit?: number;\n /** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */\n attributePerLinkCountLimit?: number;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached spans are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\n/** Interface configuration for BatchSpanProcessor on browser */\nexport interface BatchSpanProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n"]}