"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.parseSpanOptions = parseSpanOptions; exports.withSpan = withSpan; var _elasticApmNode = _interopRequireDefault(require("elastic-apm-node")); var _async_hooks = _interopRequireDefault(require("async_hooks")); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ function parseSpanOptions(optionsOrName) { const options = typeof optionsOrName === 'string' ? { name: optionsOrName } : optionsOrName; return options; } const runInNewContext = cb => { const resource = new _async_hooks.default.AsyncResource('fake_async'); return resource.runInAsyncScope(cb); }; async function withSpan(optionsOrName, cb) { const options = parseSpanOptions(optionsOrName); const { name, type, subtype, labels, intercept } = options; if (!_elasticApmNode.default.isStarted()) { return cb(); } let createdSpan; // When a span starts, it's marked as the active span in its context. // When it ends, it's not untracked, which means that if a span // starts directly after this one ends, the newly started span is a // child of this span, even though it should be a sibling. // To mitigate this, we queue a microtask by awaiting a promise. if (!intercept) { var _agent$startSpan; await Promise.resolve(); createdSpan = (_agent$startSpan = _elasticApmNode.default.startSpan(name)) !== null && _agent$startSpan !== void 0 ? _agent$startSpan : undefined; if (!createdSpan) { return cb(); } } // If a span is created in the same context as the span that we just // started, it will be a sibling, not a child. E.g., the Elasticsearch span // that is created when calling search() happens in the same context. To // mitigate this we create a new context. return runInNewContext(() => { const promise = cb(createdSpan); let span = createdSpan; if (intercept) { var _agent$currentSpan; span = (_agent$currentSpan = _elasticApmNode.default.currentSpan) !== null && _agent$currentSpan !== void 0 ? _agent$currentSpan : undefined; } if (!span) { return promise; } const targetedSpan = span; if (name) { targetedSpan.name = name; } // @ts-ignore if (type) { targetedSpan.type = type; } if (subtype) { targetedSpan.subtype = subtype; } if (labels) { targetedSpan.addLabels(labels); } return promise.then(res => { if (!targetedSpan.outcome || targetedSpan.outcome === 'unknown') { targetedSpan.outcome = 'success'; } return res; }).catch(err => { if (!targetedSpan.outcome || targetedSpan.outcome === 'unknown') { targetedSpan.outcome = 'failure'; } throw err; }).finally(() => { targetedSpan.end(); }); }); }