UNPKG

8.07 kBJavaScriptView Raw
1"use strict";
2/*
3 * Copyright The OpenTelemetry Authors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17Object.defineProperty(exports, "__esModule", { value: true });
18exports.BasicTracerProvider = exports.ForceFlushState = void 0;
19const api_1 = require("@opentelemetry/api");
20const core_1 = require("@opentelemetry/core");
21const resources_1 = require("@opentelemetry/resources");
22const _1 = require(".");
23const config_1 = require("./config");
24const MultiSpanProcessor_1 = require("./MultiSpanProcessor");
25const NoopSpanProcessor_1 = require("./export/NoopSpanProcessor");
26// eslint-disable-next-line @typescript-eslint/no-var-requires
27const merge = require('lodash.merge');
28const platform_1 = require("./platform");
29var ForceFlushState;
30(function (ForceFlushState) {
31 ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
32 ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
33 ForceFlushState[ForceFlushState["error"] = 2] = "error";
34 ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
35})(ForceFlushState = exports.ForceFlushState || (exports.ForceFlushState = {}));
36/**
37 * This class represents a basic tracer provider which platform libraries can extend
38 */
39class BasicTracerProvider {
40 constructor(config = {}) {
41 var _a;
42 this._registeredSpanProcessors = [];
43 this._tracers = new Map();
44 const mergedConfig = merge({}, config_1.DEFAULT_CONFIG, config);
45 this.resource = (_a = mergedConfig.resource) !== null && _a !== void 0 ? _a : resources_1.Resource.empty();
46 this.resource = resources_1.Resource.default().merge(this.resource);
47 this._config = Object.assign({}, mergedConfig, {
48 resource: this.resource,
49 });
50 const defaultExporter = this._buildExporterFromEnv();
51 if (defaultExporter !== undefined) {
52 const batchProcessor = new platform_1.BatchSpanProcessor(defaultExporter);
53 this.activeSpanProcessor = batchProcessor;
54 }
55 else {
56 this.activeSpanProcessor = new NoopSpanProcessor_1.NoopSpanProcessor();
57 }
58 }
59 getTracer(name, version) {
60 const key = `${name}@${version || ''}`;
61 if (!this._tracers.has(key)) {
62 this._tracers.set(key, new _1.Tracer({ name, version }, this._config, this));
63 }
64 return this._tracers.get(key);
65 }
66 /**
67 * Adds a new {@link SpanProcessor} to this tracer.
68 * @param spanProcessor the new SpanProcessor to be added.
69 */
70 addSpanProcessor(spanProcessor) {
71 if (this._registeredSpanProcessors.length === 0) {
72 // since we might have enabled by default a batchProcessor, we disable it
73 // before adding the new one
74 this.activeSpanProcessor
75 .shutdown()
76 .catch(err => api_1.diag.error('Error while trying to shutdown current span processor', err));
77 }
78 this._registeredSpanProcessors.push(spanProcessor);
79 this.activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(this._registeredSpanProcessors);
80 }
81 getActiveSpanProcessor() {
82 return this.activeSpanProcessor;
83 }
84 /**
85 * Register this TracerProvider for use with the OpenTelemetry API.
86 * Undefined values may be replaced with defaults, and
87 * null values will be skipped.
88 *
89 * @param config Configuration object for SDK registration
90 */
91 register(config = {}) {
92 api_1.trace.setGlobalTracerProvider(this);
93 if (config.propagator === undefined) {
94 config.propagator = this._buildPropagatorFromEnv();
95 }
96 if (config.contextManager) {
97 api_1.context.setGlobalContextManager(config.contextManager);
98 }
99 if (config.propagator) {
100 api_1.propagation.setGlobalPropagator(config.propagator);
101 }
102 }
103 forceFlush() {
104 const timeout = this._config.forceFlushTimeoutMillis;
105 const promises = this._registeredSpanProcessors.map((spanProcessor) => {
106 return new Promise(resolve => {
107 let state;
108 const timeoutInterval = setTimeout(() => {
109 resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
110 state = ForceFlushState.timeout;
111 }, timeout);
112 spanProcessor
113 .forceFlush()
114 .then(() => {
115 clearTimeout(timeoutInterval);
116 if (state !== ForceFlushState.timeout) {
117 state = ForceFlushState.resolved;
118 resolve(state);
119 }
120 })
121 .catch(error => {
122 clearTimeout(timeoutInterval);
123 state = ForceFlushState.error;
124 resolve(error);
125 });
126 });
127 });
128 return new Promise((resolve, reject) => {
129 Promise.all(promises)
130 .then(results => {
131 const errors = results.filter(result => result !== ForceFlushState.resolved);
132 if (errors.length > 0) {
133 reject(errors);
134 }
135 else {
136 resolve();
137 }
138 })
139 .catch(error => reject([error]));
140 });
141 }
142 shutdown() {
143 return this.activeSpanProcessor.shutdown();
144 }
145 _getPropagator(name) {
146 var _a;
147 return (_a = BasicTracerProvider._registeredPropagators.get(name)) === null || _a === void 0 ? void 0 : _a();
148 }
149 _getSpanExporter(name) {
150 var _a;
151 return (_a = BasicTracerProvider._registeredExporters.get(name)) === null || _a === void 0 ? void 0 : _a();
152 }
153 _buildPropagatorFromEnv() {
154 // per spec, propagators from env must be deduplicated
155 const uniquePropagatorNames = Array.from(new Set(core_1.getEnv().OTEL_PROPAGATORS));
156 const propagators = uniquePropagatorNames.map(name => {
157 const propagator = this._getPropagator(name);
158 if (!propagator) {
159 api_1.diag.warn(`Propagator "${name}" requested through environment variable is unavailable.`);
160 }
161 return propagator;
162 });
163 const validPropagators = propagators.reduce((list, item) => {
164 if (item) {
165 list.push(item);
166 }
167 return list;
168 }, []);
169 if (validPropagators.length === 0) {
170 return;
171 }
172 else if (uniquePropagatorNames.length === 1) {
173 return validPropagators[0];
174 }
175 else {
176 return new core_1.CompositePropagator({
177 propagators: validPropagators,
178 });
179 }
180 }
181 _buildExporterFromEnv() {
182 const exporterName = core_1.getEnv().OTEL_TRACES_EXPORTER;
183 if (exporterName === 'none')
184 return;
185 const exporter = this._getSpanExporter(exporterName);
186 if (!exporter) {
187 api_1.diag.error(`Exporter "${exporterName}" requested through environment variable is unavailable.`);
188 }
189 return exporter;
190 }
191}
192exports.BasicTracerProvider = BasicTracerProvider;
193BasicTracerProvider._registeredPropagators = new Map([
194 ['tracecontext', () => new core_1.HttpTraceContextPropagator()],
195 ['baggage', () => new core_1.HttpBaggagePropagator()],
196]);
197BasicTracerProvider._registeredExporters = new Map();
198//# sourceMappingURL=BasicTracerProvider.js.map
\No newline at end of file