Instrumentation.prototype.addEndedSpan = function()

in lib/instrumentation/index.js [776:842]


Instrumentation.prototype.addEndedSpan = function (span) {
  var agent = this._agent;

  if (!this._started) {
    agent.logger.debug('ignoring span %o', {
      span: span.id,
      parent: span.parentId,
      trace: span.traceId,
      name: span.name,
      type: span.type,
    });
    return;
  }

  // Replace the active run context with this span removed. Typically this
  // span is the top of stack (i.e. is the current span). However, it is
  // possible to have out-of-order span.end(), in which case the ended span
  // might not.
  const newRc = this._runCtxMgr.active().leaveSpan(span);
  if (newRc) {
    this._runCtxMgr.supersedeRunContext(newRc);
  }
  this._log.debug(
    { ctxmgr: this._runCtxMgr.toString() },
    'addEndedSpan(%s)',
    span.name,
  );

  // Avoid span encoding time if only propagating trace-context.
  if (agent._conf.contextPropagationOnly) {
    return;
  }

  if (!span.isRecorded()) {
    span.transaction.captureDroppedSpan(span);
    return;
  }

  if (!this._agent._conf.spanCompressionEnabled) {
    this._encodeAndSendSpan(span);
  } else {
    // if I have ended and I have something buffered, send that buffered thing
    if (span.getBufferedSpan()) {
      this._encodeAndSendSpan(span.getBufferedSpan());
      span.setBufferedSpan(null);
    }

    const parentSpan = span.getParentSpan();
    if ((parentSpan && parentSpan.ended) || !span.isCompressionEligible()) {
      const buffered = parentSpan && parentSpan.getBufferedSpan();
      if (buffered) {
        this._encodeAndSendSpan(buffered);
        parentSpan.setBufferedSpan(null);
      }
      this._encodeAndSendSpan(span);
    } else if (!parentSpan.getBufferedSpan()) {
      // span is compressible and there's nothing buffered
      // add to buffer, move on
      parentSpan.setBufferedSpan(span);
    } else if (!parentSpan.getBufferedSpan().tryToCompress(span)) {
      // we could not compress span so SEND bufferend span
      // and buffer the span we could not compress
      this._encodeAndSendSpan(parentSpan.getBufferedSpan());
      parentSpan.setBufferedSpan(span);
    }
  }
};