| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296 |
1×
1×
1×
1×
1×
1×
1×
103×
103×
103×
103×
103×
103×
103×
103×
103×
7×
3×
13×
1×
13×
12×
12×
6×
6×
6×
6×
6×
3×
3×
3×
8×
8×
283×
8×
262×
7×
7×
1×
6×
6×
6×
5×
5×
6×
6×
57×
1×
1×
56×
56×
55×
55×
55×
167×
167×
165×
112×
112×
112×
167×
86×
2×
2×
84×
84×
84×
9×
9×
4×
2×
2×
4×
| // @flow
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import * as constants from './constants.js';
import SpanContext from './span_context.js';
import * as opentracing from 'opentracing';
import Utils from './util.js';
import BaggageSetter from './baggage/baggage_setter';
export default class Span {
_tracer: any;
_operationName: string;
_spanContext: SpanContext;
_startTime: number;
_logger: any;
_duration: number;
_logs: Array<LogData>;
_tags: Array<Tag>;
static _baggageHeaderCache: any;
_references: Array<Reference>;
_baggageSetter: BaggageSetter;
constructor(tracer: any,
operationName: string,
spanContext: SpanContext,
startTime: number,
references: Array<Reference>
) {
this._tracer = tracer;
this._operationName = operationName;
this._spanContext = spanContext;
this._startTime = startTime;
this._logger = tracer._logger;
this._references = references;
this._baggageSetter = tracer._baggageSetter;
this._logs = [];
this._tags = [];
}
get operationName(): string {
return this._operationName;
}
get serviceName(): string {
return this._tracer._serviceName;
}
static _getBaggageHeaderCache() {
if (!Span._baggageHeaderCache) {
Span._baggageHeaderCache = {};
}
return Span._baggageHeaderCache;
}
/**
* Returns a normalize key.
*
* @param {string} key - The key to be normalized for a particular baggage value.
* @return {string} - The normalized key (lower cased and underscores replaced, along with dashes.)
**/
_normalizeBaggageKey(key: string) {
let baggageHeaderCache = Span._getBaggageHeaderCache();
if (key in baggageHeaderCache) {
return baggageHeaderCache[key];
}
let normalizedKey: string = key.replace(/_/g, '-').toLowerCase();
if (EObject.keys(baggageHeaderCache).length < 100) {
baggageHeaderCache[key] = normalizedKey;
}
return normalizedKey;
}
/**
* Sets a baggage value with an associated key.
*
* @param {string} key - The baggage key.
* @param {string} value - The baggage value.
*
* @return {Span} - returns this span.
**/
setBaggageItem(key: string, value: string): Span {
let normalizedKey = this._normalizeBaggageKey(key);
// We create a new instance of the context here instead of just adding
// another entry to the baggage dictionary. By doing so we keep the
// baggage immutable so that it can be passed to children spans as is.
// If it was mutable, we would have to make a copy of the dictionary
// for every child span, which on average we expect to occur more
// frequently than items being added to the baggage.
this._spanContext = this._baggageSetter.setBaggage(this, normalizedKey, value);
return this;
}
/**
* Gets a baggage value with an associated key.
*
* @param {string} key - The baggage key.
* @return {string} value - The baggage value.
**/
getBaggageItem(key: string): string {
let normalizedKey = this._normalizeBaggageKey(key);
return this._spanContext.baggage[normalizedKey];
}
/**
* Returns the span context that represents this span.
*
* @return {SpanContext} - Returns this span's span context.
**/
context(): SpanContext {
return this._spanContext;
}
/**
* Returns the tracer associated with this span.
this._duration;
* @return {Tracer} - returns the tracer associated witht this span.
**/
tracer(): any {
return this._tracer;
}
/**
* Checks whether or not a span can be written to.
*
* @return {boolean} - The decision about whether this span can be written to.
**/
_isWriteable(): boolean {
return !this._spanContext.samplingFinalized || this._spanContext.isSampled();
}
/**
* Sets the operation name on this given span.
*
* @param {string} name - The name to use for setting a span's operation name.
* @return {Span} - returns this span.
**/
setOperationName(operationName: string): Span {
this._operationName = operationName;
// We re-sample the span if it has not been finalized.
if (this._spanContext.samplingFinalized) {
return this;
}
let sampler = this.tracer()._sampler;
let tags = {};
if (sampler.isSampled(operationName, tags)) {
this._spanContext.flags |= constants.SAMPLED_MASK;
this.addTags(tags);
}
this._spanContext.finalizeSampling();
return this;
}
/**
* Sets the end timestamp and finalizes Span state.
*
* With the exception of calls to Span.context() (which are always allowed),
* finish() must be the last call made to any span instance, and to do
* otherwise leads to undefined behavior.
*
* @param {number} finishTime
* Optional finish time in milliseconds as a Unix timestamp. Decimal
* values are supported for timestamps with sub-millisecond accuracy.
* If not specified, the current time (as defined by the
* implementation) will be used.
*/
finish(finishTime: ?number): void {
if (this._duration !== undefined) {
let spanInfo = `operation=${this.operationName},context=${this.context().toString()}`;
this.tracer()._logger.error(`${spanInfo}#You can only call finish() on a span once.`);
return;
}
this._spanContext.finalizeSampling();
if (this._spanContext.isSampled()) {
let endTime = finishTime || this._tracer.now();
this._duration = endTime - this._startTime;
this._tracer._report(this);
}
}
/**
* Adds a set of tags to a span.
*
* @param {Object} keyValuePairs - An object with key value pairs
* that represent tags to be added to this span.
* @return {Span} - returns this span.
**/
addTags(keyValuePairs: any): Span {
if (Iopentracing.Tags.SAMPLING_PRIORITY in keyValuePairs) {
this._setSamplingPriority(keyValuePairs[opentracing.Tags.SAMPLING_PRIORITY]);
delete keyValuePairs[opentracing.Tags.SAMPLING_PRIORITY];
}
if (this._isWriteable()) {
for (let key in keyValuePairs) {
if (EkeyValuePairs.hasOwnProperty(key)) {
let value = keyValuePairs[key];
this._tags.push({'key': key, 'value': value});
}
}
}
return this;
}
/**
* Adds a single tag to a span
*
* @param {string} key - The key for the tag added to this span.
* @param {string} value - The value corresponding with the key
* for the tag added to this span.
* @return {Span} - returns this span.
* */
setTag(key: string, value: any): Span {
if (key === opentracing.Tags.SAMPLING_PRIORITY) {
this._setSamplingPriority(value);
return this;
}
if (Ethis._isWriteable()) {
this._tags.push({'key': key, 'value': value});
}
return this;
}
/**
* Adds a log event, or payload to a span.
*
* @param {object} keyValuePairs
* An object mapping string keys to arbitrary value types. All
* Tracer implementations should support bool, string, and numeric
* value types, and some may also support Object values.
* @param {number} timestamp
* An optional parameter specifying the timestamp in milliseconds
* since the Unix epoch. Fractional values are allowed so that
* timestamps with sub-millisecond accuracy can be represented. If
* not specified, the implementation is expected to use its notion
* of the current time of the call.
*/
log(keyValuePairs: any, timestamp: ?number): void {
if (Ethis._isWriteable()) {
this._logs.push({
'timestamp': timestamp || this._tracer.now(),
'fields': Utils.convertObjectToTags(keyValuePairs)
});
}
}
/**
* Logs a event with an optional payload.
*
* @param {string} eventName - string associated with the log record
* @param {object} [payload] - arbitrary payload object associated with the
* log record.
*/
logEvent(eventName: string, payload: any): void {
return this.log({
event: eventName,
payload: payload
});
}
_setSamplingPriority(priority: number): void {
if (priority > 0) {
this._spanContext.flags = this._spanContext.flags | constants.SAMPLED_MASK | constants.DEBUG_MASK;
} else {
this._spanContext.flags = this._spanContext.flags & (~constants.SAMPLED_MASK);
}
this._spanContext.finalizeSampling();
}
}
|