all files / src/ span.js

94.2% Statements 65/69
78.13% Branches 25/32
100% Functions 16/16
94.03% Lines 63/67
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                                                                          131× 131×   131× 131× 131× 131× 131× 131× 131× 131× 131×       56×             18×     18×                   17× 17×                                                                   314×                                                     54×       53× 53× 53× 53×                       277×         277× 273× 260× 260× 260×       277×                       99×         99× 99×   99×                                                                      
// @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 NullLogger from './logger.js';
import SpanContext from './span_context.js';
import {Tags as opentracing_tags} from 'opentracing';
import Utils from './util.js';
 
export default class Span {
    _tracer: any;
    _operationName: string;
    _spanContext: SpanContext;
    _startTime: number;
    _logger: any;
    _duration: number;
    _firstInProcess: boolean;
    _logs: Array<LogData>;
    _tags: Array<Tag>;
    static _baggageHeaderCache: any;
    _references: Array<Reference>;
 
    constructor(tracer: any,
                operationName: string,
                spanContext: SpanContext,
                startTime: number,
                firstInProcess: boolean = false,
                references: Array<Reference>
    ) {
        this._tracer = tracer;
        this._operationName = operationName;
        this._spanContext = spanContext;
        this._startTime = startTime;
        this._logger = tracer._logger;
        this._firstInProcess = firstInProcess;
        this._references = references;
        this._logs = [];
        this._tags = [];
    }
 
    get firstInProcess(): boolean {
        return this._firstInProcess;
    }
 
    get operationName(): string {
        return this._operationName;
    }
 
    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);
        this._spanContext = this._spanContext.withBaggageItem(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;
    }
 
    /**
     * 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;
        return this;
    }
 
    /**
     * Finishes a span which has the effect of reporting it and
     * setting the finishTime on the span.
     *
     * @param {number} finishTime - The time on which this span finished.
     **/
    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;
        }
 
        if (Ethis._spanContext.isSampled()) {
            let endTime = finishTime || Utils.getTimestampMicros();
            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._spanContext.isSampled()) {
            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 (Ikey === opentracing_tags.SAMPLING_PRIORITY) {
            this._setSamplingPriority(value);
            return this;
        }
 
        if (Ethis._spanContext.isSampled()) {
            this._tags.push({'key': key, 'value': value});
        }
        return this;
    }
 
    /**
     * Adds a log event, or payload to a span.
     *
     * @param {Object} keyValuePairs - an object that represents the keyValuePairs to log.
     * @param {number} [timestamp] - the starting timestamp of a span.
     **/
    log(keyValuePairs: any, timestamp: ?number): void {
        if (Ethis._spanContext.isSampled()) {
 
            this._logs.push({
                'timestamp': timestamp || Utils.getTimestampMicros(),
                '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);
        }
    }
}