UNPKG

8.12 kBJavaScriptView Raw
1"use strict";
2/**
3 * Copyright 2018, OpenCensus 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 * http://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.CoreTracerBase = void 0;
19const uuid = require("uuid");
20const logger = require("../../common/console-logger");
21const noop_propagation_1 = require("../propagation/noop-propagation");
22const sampler_1 = require("../sampler/sampler");
23const no_record_root_span_1 = require("./no-record/no-record-root-span");
24const no_record_span_1 = require("./no-record/no-record-span");
25const root_span_1 = require("./root-span");
26const types = require("./types");
27/**
28 * This class represents a tracer.
29 */
30class CoreTracerBase {
31 /** Constructs a new TraceImpl instance. */
32 constructor() {
33 /** A list of end span event listeners */
34 this.eventListenersLocal = [];
35 /** Bit to represent whether trace is sampled or not. */
36 this.IS_SAMPLED = 0x1;
37 /** An object to log information */
38 this.logger = logger.logger();
39 this.activeLocal = false;
40 this.activeTraceParams = {};
41 }
42 /** A propagation instance */
43 get propagation() {
44 if (this.config && this.config.propagation) {
45 return this.config.propagation;
46 }
47 return noop_propagation_1.noopPropagation;
48 }
49 /** Sets the current root span. */
50 setCurrentRootSpan(root) {
51 // no-op, this is only required in case of tracer with cls.
52 }
53 /**
54 * Starts a tracer.
55 * @param config A tracer configuration object to start a tracer.
56 */
57 start(config) {
58 this.activeLocal = true;
59 this.config = config;
60 this.logger = this.config.logger || logger.logger();
61 this.sampler = sampler_1.SamplerBuilder.getSampler(config.samplingRate || sampler_1.DEFAULT_SAMPLING_RATE);
62 if (config.traceParams) {
63 this.activeTraceParams.numberOfAnnontationEventsPerSpan = sampler_1.TraceParamsBuilder.getNumberOfAnnotationEventsPerSpan(config.traceParams);
64 this.activeTraceParams.numberOfAttributesPerSpan = sampler_1.TraceParamsBuilder.getNumberOfAttributesPerSpan(config.traceParams);
65 this.activeTraceParams.numberOfMessageEventsPerSpan = sampler_1.TraceParamsBuilder.getNumberOfMessageEventsPerSpan(config.traceParams);
66 this.activeTraceParams.numberOfLinksPerSpan = sampler_1.TraceParamsBuilder.getNumberOfLinksPerSpan(config.traceParams);
67 }
68 return this;
69 }
70 /** Stops the tracer. */
71 stop() {
72 this.activeLocal = false;
73 return this;
74 }
75 /** Gets the list of event listeners. */
76 get eventListeners() {
77 return this.eventListenersLocal;
78 }
79 /** Indicates if the tracer is active or not. */
80 get active() {
81 return this.activeLocal;
82 }
83 /**
84 * Starts a root span.
85 * @param options A TraceOptions object to start a root span.
86 * @param fn A callback function to run after starting a root span.
87 */
88 startRootSpan(options, fn) {
89 const spanContext = options.spanContext || {
90 spanId: '',
91 traceId: uuid
92 .v4()
93 .split('-')
94 .join(''),
95 };
96 const parentSpanId = spanContext.spanId;
97 const traceId = spanContext.traceId;
98 const name = options.name || 'span';
99 const kind = options.kind || types.SpanKind.UNSPECIFIED;
100 const traceState = spanContext.traceState;
101 // Tracer is active
102 if (this.active) {
103 const sampleDecision = this.makeSamplingDecision(options, traceId);
104 // Sampling is on
105 if (sampleDecision) {
106 const rootSpan = new root_span_1.RootSpan(this, name, kind, traceId, parentSpanId, traceState);
107 // Add default attributes
108 const defaultAttributes = this.config && this.config.defaultAttributes;
109 if (defaultAttributes) {
110 Object.keys(defaultAttributes).forEach(key => {
111 rootSpan.addAttribute(key, defaultAttributes[key]);
112 });
113 }
114 rootSpan.start();
115 return fn(rootSpan);
116 }
117 // Sampling is off
118 this.logger.debug('Sampling is off, starting new no record root span');
119 }
120 else {
121 // Tracer is inactive
122 this.logger.debug('Tracer is inactive, starting new no record root span');
123 }
124 const noRecordRootSpan = new no_record_root_span_1.NoRecordRootSpan(this, name, kind, traceId, parentSpanId, traceState);
125 return fn(noRecordRootSpan);
126 }
127 /** Notifies listeners of the span start. */
128 onStartSpan(span) {
129 if (!this.active)
130 return;
131 this.notifyStartSpan(span);
132 }
133 /** Notifies listeners of the span end. */
134 onEndSpan(span) {
135 if (!this.active)
136 return;
137 this.notifyEndSpan(span);
138 }
139 /**
140 * Registers an end span event listener.
141 * @param listener The listener to register.
142 */
143 registerSpanEventListener(listener) {
144 this.eventListenersLocal.push(listener);
145 }
146 /**
147 * Unregisters an end span event listener.
148 * @param listener The listener to unregister.
149 */
150 unregisterSpanEventListener(listener) {
151 const index = this.eventListenersLocal.indexOf(listener, 0);
152 if (index > -1) {
153 this.eventListeners.splice(index, 1);
154 }
155 }
156 notifyStartSpan(span) {
157 this.logger.debug('starting to notify listeners the start of spans');
158 for (const listener of this.eventListenersLocal) {
159 listener.onStartSpan(span);
160 }
161 }
162 notifyEndSpan(span) {
163 this.logger.debug('starting to notify listeners the end of spans');
164 for (const listener of this.eventListenersLocal) {
165 listener.onEndSpan(span);
166 }
167 }
168 /**
169 * Starts a span.
170 * @param [options] A SpanOptions object to start a child span.
171 */
172 startChildSpan(options) {
173 if (!options || !options.childOf) {
174 this.logger.debug('no current trace found - must start a new root span first');
175 return new no_record_span_1.NoRecordSpan(this);
176 }
177 const span = options.childOf.startChildSpan(options);
178 // Add default attributes
179 const defaultAttributes = this.config && this.config.defaultAttributes;
180 if (defaultAttributes) {
181 Object.keys(defaultAttributes).forEach(key => {
182 span.addAttribute(key, defaultAttributes[key]);
183 });
184 }
185 return span;
186 }
187 /** Determine whether to sample request or not. */
188 makeSamplingDecision(options, traceId) {
189 // If users set a specific sampler in the TraceOptions, use it.
190 if (options &&
191 options.samplingRate !== undefined &&
192 options.samplingRate !== null) {
193 return sampler_1.SamplerBuilder.getSampler(options.samplingRate).shouldSample(traceId);
194 }
195 let propagatedSample = null;
196 // if there is a context propagation, keep the decision
197 if (options &&
198 options.spanContext &&
199 options.spanContext.options !== undefined) {
200 propagatedSample = (options.spanContext.options & this.IS_SAMPLED) !== 0;
201 return !!propagatedSample;
202 }
203 // default global sampler
204 return this.sampler.shouldSample(traceId);
205 }
206}
207exports.CoreTracerBase = CoreTracerBase;
208//# sourceMappingURL=tracer-base.js.map
\No newline at end of file