├── .ci └── scripts │ └── docker-test.sh ├── .github └── workflows │ ├── opentelemetry.yml │ └── test.yml ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── lib ├── span.js ├── span_context.js ├── tracer.js └── unsampled_span.js ├── package.json ├── test ├── opentracing │ └── index.js ├── span.js ├── tracer.js └── utils │ └── index.js ├── tsconfig.json └── types.d.ts /.ci/scripts/docker-test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -exuo pipefail 3 | 4 | NODE_VERSION=${1:?Nodejs version missing NODE_VERSION is not set} 5 | USER_ID="$(id -u):$(id -g)" 6 | 7 | docker run --rm -t \ 8 | -v $(pwd):/src \ 9 | -w /src \ 10 | -u "${USER_ID}" \ 11 | -e HOME=/tmp \ 12 | -e CI=true \ 13 | --name "node-${NODE_VERSION}" \ 14 | node:${NODE_VERSION} \ 15 | /bin/bash -c """ 16 | node --version 17 | npm --version 18 | npm install 19 | npm test | tee test-suite-output.tap 20 | """ 21 | -------------------------------------------------------------------------------- /.github/workflows/opentelemetry.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: OpenTelemetry Export Trace 3 | 4 | on: 5 | workflow_run: 6 | workflows: 7 | - test 8 | types: [completed] 9 | 10 | jobs: 11 | otel-export-trace: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: elastic/apm-pipeline-library/.github/actions/opentelemetry@current 15 | with: 16 | vaultUrl: ${{ secrets.VAULT_ADDR }} 17 | vaultRoleId: ${{ secrets.VAULT_ROLE_ID }} 18 | vaultSecretId: ${{ secrets.VAULT_SECRET_ID }} 19 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | # https://github.community/t/how-to-trigger-an-action-on-push-or-pull-request-but-not-both/16662/2 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | jobs: 11 | test-vers: 12 | strategy: 13 | matrix: 14 | # Test with the latest supported release. 15 | node: ['12'] 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v2 19 | - uses: actions/setup-node@v2 20 | with: 21 | node-version: ${{ matrix.node }} 22 | - run: npm install 23 | - run: npm test 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | test-suite-output.tap 3 | junit-test-suite-*.xml 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .travis.yml 2 | test 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Elasticsearch BV 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Elastic APM Node.js OpenTracing Bridge 2 | 3 | **Note: This OpenTracing Bridge is deprecated in favor of the [Elastic APM Node.js OpenTelemetry Bridge](https://www.elastic.co/guide/en/apm/agent/nodejs/current/opentelemetry-bridge.html)** 4 | 5 | An [OpenTracing](https://opentracing.io/) bridge for the [Elastic APM Node.js Agent](https://github.com/elastic/apm-agent-nodejs). 6 | 7 | [![npm](https://img.shields.io/npm/v/elastic-apm-node-opentracing.svg)](https://www.npmjs.com/package/elastic-apm-node-opentracing) 8 | [![Test status](https://github.com/elastic/apm-agent-nodejs-opentracing/workflows/Test/badge.svg)](https://github.com/elastic/apm-agent-nodejs-opentracingactions) 9 | [![Build Status](https://github.com/elastic/apm-agent-nodejs-opentracing/actions/workflows/test.yml/badge.svg)](https://github.com/elastic/apm-agent-nodejs-opentracing/actions/workflows/test.yml) 10 | 11 | ## Prerequisites 12 | 13 | This module have [`elastic-apm-node`](https://www.npmjs.com/package/elastic-apm-node) as a peer dependency. 14 | 15 | Version 2.10.0 or higher of the Elastic APM Agent is required in order to use this module. 16 | 17 | ## Installation 18 | 19 | ``` 20 | npm install elastic-apm-node-opentracing --save 21 | ``` 22 | 23 | ## Usage 24 | 25 | ```js 26 | // Start the Elastic APM agent at the VERY top of the first file loaded 27 | // in your app 28 | const agent = require('elastic-apm-node').start() 29 | const Tracer = require('elastic-apm-node-opentracing') 30 | 31 | // Pass the Elastic APM agent as an argument to the OpenTracing tracer 32 | const tracer = new Tracer(agent) 33 | 34 | const span = tracer.startSpan('my-first-span') 35 | // ... do some work ... 36 | span.finish() 37 | ``` 38 | 39 | ## API 40 | 41 | ### `tracer = new Tracer(agent)` 42 | 43 | This module exposes a `Tracer` class which is OpenTracing compatible. 44 | 45 | When instantiating the `Tracer` object, 46 | an instance of the Elastic APM Node.js Agent must be provided as its only argument. 47 | 48 | For details about the `tracer` API, 49 | see the [`opentracing-javascript` API docs](https://opentracing-javascript.surge.sh/). 50 | 51 | ## License 52 | 53 | [Apache-2.0](LICENSE) 54 | -------------------------------------------------------------------------------- /lib/span.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const opentracing = require('opentracing') 4 | const SpanContext = require('./span_context') 5 | 6 | const illigalChars = /[.*"]/g 7 | 8 | class Span extends opentracing.Span { 9 | constructor (tracer, span) { 10 | super() 11 | this.__tracer = tracer 12 | this.__context = null 13 | this._span = span 14 | this._isTransaction = !!span.setUserContext 15 | } 16 | 17 | _context () { 18 | return this.__context 19 | ? this.__context 20 | : (this.__context = new SpanContext(this._span)) 21 | } 22 | 23 | _tracer () { 24 | return this.__tracer 25 | } 26 | 27 | _setOperationName (name) { 28 | this._span.name = name 29 | } 30 | 31 | // Override the addTags function in order to be able to call _addTags 32 | // elsewhere without triggering the clone of `tags` 33 | addTags (tags) { 34 | // We might delete tags in _addTags, so clone in order not to mutate 35 | this._addTags(Object.assign({}, tags)) 36 | return this 37 | } 38 | 39 | _addTags (tags) { 40 | if (this._isTransaction) { 41 | if ('error' in tags) { 42 | this._span.result = tags.error ? 'error' : 'success' 43 | delete tags.error 44 | } else if (tags.result) { 45 | this._span.result = tags.result 46 | delete tags.result 47 | } else if (tags['http.status_code']) { 48 | this._span.result = `HTTP ${String(tags['http.status_code'])[0]}xx` 49 | delete tags['http.status_code'] // TODO: Should this be allowed to be stored? 50 | } 51 | 52 | const id = tags['user.id'] 53 | const username = tags['user.username'] 54 | const email = tags['user.email'] 55 | if (id || username || email) { 56 | this._span.setUserContext({ id, username, email }) 57 | delete tags['user.id'] 58 | delete tags['user.username'] 59 | delete tags['user.email'] 60 | } 61 | } 62 | 63 | if (tags.type) { 64 | this._span.type = tags.type 65 | delete tags.type 66 | } 67 | 68 | const keys = Object.keys(tags) 69 | 70 | if (keys.length === 0) return 71 | 72 | // While the Node.js agent will sanitize the keys for us, it will also log 73 | // a warning each time. As periods are the norm in OpenTracing, we don't 74 | // want to log a warning each time a period is found, so we'll sanitize the 75 | // keys before forwarding the tags to the agent 76 | const sanitizedTags = {} 77 | for (const key of keys) { 78 | const sanitizedKey = key.replace(illigalChars, '_') 79 | sanitizedTags[sanitizedKey] = tags[key] 80 | } 81 | 82 | this._span.addLabels(sanitizedTags) 83 | } 84 | 85 | _log (logs, timestamp) { 86 | if (logs.event === 'error') { 87 | if (logs['error.object']) { 88 | this.__tracer._agent.captureError(logs['error.object'], { timestamp, message: logs.message }) 89 | } else if (logs.message) { 90 | this.__tracer._agent.captureError(logs.message, { timestamp }) 91 | } 92 | } 93 | } 94 | 95 | _finish (finishTime) { 96 | if (this._isTransaction) { 97 | this._span.end(null, finishTime) 98 | } else { 99 | this._span.end(finishTime) 100 | } 101 | } 102 | } 103 | 104 | module.exports = Span 105 | -------------------------------------------------------------------------------- /lib/span_context.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const opentracing = require('opentracing') 4 | 5 | class SpanContext extends opentracing.SpanContext { 6 | // `context` can either be a string or a Span or Transaction object from the 7 | // elastic-apm-module 8 | constructor (context) { 9 | super() 10 | this._context = context 11 | } 12 | 13 | toString () { 14 | return typeof this._context === 'string' 15 | ? this._context 16 | : this._context.traceparent // TODO: This is a breaking change as not all versions of the agent has this property 17 | } 18 | } 19 | 20 | module.exports = SpanContext 21 | -------------------------------------------------------------------------------- /lib/tracer.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const opentracing = require('opentracing') 4 | const Span = require('./span') 5 | const UnsampledSpan = require('./unsampled_span') 6 | const SpanContext = require('./span_context') 7 | 8 | class Tracer extends opentracing.Tracer { 9 | constructor (agent) { 10 | super() 11 | if (!agent) throw new Error('Missing required argument: agent') 12 | this._agent = agent 13 | } 14 | 15 | _startSpan (name, opts) { 16 | let context = null 17 | 18 | if (Array.isArray(opts.references)) { 19 | if (opts.references.length > 1) { 20 | this._agent.logger.debug('Elastic APM OpenTracing: Unsupported number of references to _startSpan:', opts.references.length) 21 | } 22 | 23 | for (const i in opts.references) { 24 | const ref = opts.references[i] 25 | const refType = ref.type() 26 | // TODO: Log warning if type is REFERENCE_FOLLOWS_FROM? 27 | if (refType === opentracing.REFERENCE_CHILD_OF) { 28 | context = ref.referencedContext().toString() 29 | break 30 | } 31 | } 32 | } 33 | 34 | let tags, type 35 | 36 | if (opts.tags) { 37 | // We might delete tags leter on, so clone in order not to mutate 38 | tags = Object.assign({}, opts.tags) 39 | type = tags.type 40 | if (type) delete tags.type 41 | } 42 | 43 | let span = this._agent.currentTransaction === null || this._agent.currentTransaction.ended 44 | ? this._agent.startTransaction(name, type, { childOf: context, startTime: opts.startTime }) 45 | : this._agent.startSpan(name, type, { childOf: context, startTime: opts.startTime }) 46 | 47 | if (!span) { 48 | // The transaction wasn't sampled, but to be able to continue the trace 49 | // later using the `inject` function, we need to return a dummy span 50 | // object that can be used as a carrier for the SpanContext of the 51 | // unsampled transaction. 52 | return new UnsampledSpan(this._agent.currentTransaction) 53 | } 54 | 55 | span = new Span(this, span) 56 | 57 | if (tags && Object.keys(tags).length !== 0) span._addTags(tags) 58 | 59 | return span 60 | } 61 | 62 | _inject (spanContext, format, carrier) { 63 | switch (format) { 64 | case opentracing.FORMAT_TEXT_MAP: 65 | case opentracing.FORMAT_HTTP_HEADERS: 66 | carrier['elastic-apm-traceparent'] = spanContext.toString() 67 | break 68 | } 69 | } 70 | 71 | _extract (format, carrier) { 72 | if (typeof carrier !== 'object') return null 73 | let ctx 74 | 75 | switch (format) { 76 | case opentracing.FORMAT_TEXT_MAP: 77 | case opentracing.FORMAT_HTTP_HEADERS: 78 | ctx = carrier['elastic-apm-traceparent'] 79 | break 80 | } 81 | 82 | return ctx ? new SpanContext(ctx) : null 83 | } 84 | } 85 | 86 | module.exports = Tracer 87 | -------------------------------------------------------------------------------- /lib/unsampled_span.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const opentracing = require('opentracing') 4 | const SpanContext = require('./span_context') 5 | 6 | class UnsampledSpan extends opentracing.Span { 7 | constructor (elasticTransaction) { 8 | super() 9 | this.__context = null 10 | this._elasticTransaction = elasticTransaction 11 | this._isTransaction = false 12 | } 13 | 14 | _context () { 15 | return this.__context 16 | ? this.__context 17 | : (this.__context = new SpanContext(this._elasticTransaction)) 18 | } 19 | } 20 | 21 | module.exports = UnsampledSpan 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "elastic-apm-node-opentracing", 3 | "version": "2.0.1", 4 | "description": "An OpenTracing bridge for the Elastic APM Node.js Agent", 5 | "main": "lib/tracer.js", 6 | "types": "types.d.ts", 7 | "directories": { 8 | "test": "test" 9 | }, 10 | "scripts": { 11 | "test": "standard && mocha test/opentracing/index.js && tape test/*.js" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/elastic/apm-agent-nodejs-opentracing.git" 16 | }, 17 | "dependencies": { 18 | "opentracing": "^0.14.3" 19 | }, 20 | "devDependencies": { 21 | "chai": "^4.2.0", 22 | "elastic-apm-node": "^2.16.2", 23 | "mocha": "^5.2.0", 24 | "standard": "^12.0.1", 25 | "tape": "^4.9.2" 26 | }, 27 | "peerDependencies": { 28 | "elastic-apm-node": "^2.10.0" 29 | }, 30 | "keywords": [ 31 | "elastic", 32 | "elasticapm", 33 | "apm", 34 | "opentracing", 35 | "ot", 36 | "distributed", 37 | "tracing" 38 | ], 39 | "author": "Thomas Watson (https://twitter.com/wa7son)", 40 | "license": "Apache-2.0", 41 | "bugs": { 42 | "url": "https://github.com/elastic/apm-agent-nodejs-opentracing/issues" 43 | }, 44 | "homepage": "https://github.com/elastic/apm-agent-nodejs-opentracing#readme", 45 | "coordinates": [ 46 | 55.778281, 47 | 12.593071 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /test/opentracing/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const apiCompatibilityChecks = require('opentracing/lib/test/api_compatibility').default 4 | const Tracer = require('../..') 5 | 6 | const agent = require('elastic-apm-node').start() 7 | apiCompatibilityChecks(() => new Tracer(agent), { skipBaggageChecks: true, skipInjectExtractChecks: true }) 8 | -------------------------------------------------------------------------------- /test/span.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const test = require('tape') 4 | 5 | const { setup, getAgent } = require('./utils') 6 | const Tracer = require('..') 7 | const Transaction = require('elastic-apm-node/lib/instrumentation/transaction') 8 | 9 | test('init', setup(function (t) { 10 | const tracer = new Tracer(getAgent()) 11 | const span = tracer.startSpan() 12 | t.equal(span._isTransaction, true) 13 | t.ok(span._span instanceof Transaction) 14 | t.end() 15 | })) 16 | 17 | test('#setOperationName()', setup(function (t) { 18 | const tracer = new Tracer(getAgent()) 19 | const span = tracer.startSpan('foo') 20 | span.setOperationName('bar') 21 | t.equal(span._span.name, 'bar') 22 | t.end() 23 | })) 24 | 25 | test('tags', setup(function (t) { 26 | const tracer = new Tracer(getAgent()) 27 | const span = tracer.startSpan() 28 | 29 | const tags = { 30 | a: '1', 31 | 'a.b': '2', 32 | 'a"b': '3', 33 | 'a*b': '4' 34 | } 35 | 36 | span.addTags(tags) 37 | 38 | t.deepEqual(span._span._labels, { 39 | a: '1', 40 | a_b: '4' 41 | }, 'should set expected tags') 42 | 43 | t.deepEqual(tags, { 44 | a: '1', 45 | 'a.b': '2', 46 | 'a"b': '3', 47 | 'a*b': '4' 48 | }, 'should not mutate input') 49 | 50 | t.end() 51 | })) 52 | 53 | test('tag: type', setup(function (t) { 54 | const tracer = new Tracer(getAgent()) 55 | const span = tracer.startSpan() 56 | span.setTag('type', 'foo') 57 | t.equal(span._span.type, 'foo') 58 | t.equal(span._span._labels, null) 59 | t.end() 60 | })) 61 | 62 | test('tag: result', setup(function (t) { 63 | const tracer = new Tracer(getAgent()) 64 | const span = tracer.startSpan() 65 | span.setTag('result', 'foo') 66 | t.equal(span._span.result, 'foo') 67 | t.equal(span._span._labels, null) 68 | t.end() 69 | })) 70 | 71 | test('tag: http.status_code', setup(function (t) { 72 | const tracer = new Tracer(getAgent()) 73 | const span = tracer.startSpan() 74 | span.setTag('http.status_code', 200) 75 | t.equal(span._span.result, 'HTTP 2xx') 76 | t.equal(span._span._labels, null) 77 | t.end() 78 | })) 79 | 80 | test('tag: user.*', setup(function (t) { 81 | const tracer = new Tracer(getAgent()) 82 | const span = tracer.startSpan() 83 | span.addTags({ 84 | 'user.id': 'foo', 85 | 'user.username': 'bar', 86 | 'user.email': 'baz' 87 | }) 88 | t.deepEqual(span._span._user, { 89 | id: 'foo', 90 | username: 'bar', 91 | email: 'baz' 92 | }) 93 | t.equal(span._span._labels, null) 94 | t.end() 95 | })) 96 | 97 | test('log - error, but no details', setup(function (t) { 98 | const tracer = new Tracer(getAgent()) 99 | 100 | const captureError = tracer._agent.captureError 101 | tracer._agent.captureError = function () { 102 | t.fail('should not capture error if only the event log is set') 103 | } 104 | 105 | const span = tracer.startSpan() 106 | span.log({ event: 'error' }) 107 | t.equal(span._span._labels, null) 108 | 109 | tracer._agent.captureError = captureError 110 | t.end() 111 | })) 112 | 113 | test('log - error, with error object', setup(function (t) { 114 | const tracer = new Tracer(getAgent()) 115 | 116 | const error = new Error('foo') 117 | const captureError = tracer._agent.captureError 118 | tracer._agent.captureError = function (capturedError, opts) { 119 | t.equal(capturedError, error) 120 | t.deepEqual(opts, { 121 | timestamp: undefined, 122 | message: undefined 123 | }) 124 | } 125 | 126 | const span = tracer.startSpan() 127 | span.log({ event: 'error', 'error.object': error }) 128 | t.equal(span._span._labels, null) 129 | 130 | tracer._agent.captureError = captureError 131 | t.end() 132 | })) 133 | 134 | test('log - error, with string message', setup(function (t) { 135 | const tracer = new Tracer(getAgent()) 136 | 137 | const error = 'foo' 138 | const captureError = tracer._agent.captureError 139 | tracer._agent.captureError = function (capturedError, opts) { 140 | t.equal(capturedError, error) 141 | t.deepEqual(opts, { timestamp: undefined }) 142 | } 143 | 144 | const span = tracer.startSpan() 145 | span.log({ event: 'error', message: error }) 146 | t.equal(span._span._labels, null) 147 | 148 | tracer._agent.captureError = captureError 149 | t.end() 150 | })) 151 | 152 | test('log - error, with error object + timestamp', setup(function (t) { 153 | const tracer = new Tracer(getAgent()) 154 | 155 | const error = new Error('foo') 156 | const timestamp = Date.now() - 1000 157 | 158 | const captureError = tracer._agent.captureError 159 | tracer._agent.captureError = function (capturedError, opts) { 160 | t.equal(capturedError, error) 161 | t.deepEqual(opts, { 162 | timestamp, 163 | message: undefined 164 | }) 165 | } 166 | 167 | const span = tracer.startSpan() 168 | span.log({ event: 'error', 'error.object': error }, timestamp) 169 | t.equal(span._span._labels, null) 170 | 171 | tracer._agent.captureError = captureError 172 | t.end() 173 | })) 174 | 175 | test('log - error, with string message + timestamp', setup(function (t) { 176 | const tracer = new Tracer(getAgent()) 177 | 178 | const error = 'foo' 179 | const timestamp = Date.now() - 1000 180 | 181 | const captureError = tracer._agent.captureError 182 | tracer._agent.captureError = function (capturedError, opts) { 183 | t.equal(capturedError, error) 184 | t.deepEqual(opts, { timestamp }) 185 | } 186 | 187 | const span = tracer.startSpan() 188 | span.log({ event: 'error', message: error }, timestamp) 189 | t.equal(span._span._labels, null) 190 | 191 | tracer._agent.captureError = captureError 192 | t.end() 193 | })) 194 | 195 | test('log - error, with error object + message + timestamp', setup(function (t) { 196 | const tracer = new Tracer(getAgent()) 197 | 198 | const error = new Error('foo') 199 | const message = 'bar' 200 | const timestamp = Date.now() - 1000 201 | 202 | const captureError = tracer._agent.captureError 203 | tracer._agent.captureError = function (capturedError, opts) { 204 | t.equal(capturedError, error) 205 | t.deepEqual(opts, { 206 | timestamp, 207 | message 208 | }) 209 | } 210 | 211 | const span = tracer.startSpan() 212 | span.log({ event: 'error', 'error.object': error, message }, timestamp) 213 | t.equal(span._span._labels, null) 214 | 215 | tracer._agent.captureError = captureError 216 | t.end() 217 | })) 218 | 219 | test('#finish() - transaction', setup(function (t) { 220 | const tracer = new Tracer(getAgent()) 221 | const span = tracer.startSpan('foo') 222 | t.equal(span._span.ended, false) 223 | span.finish() 224 | t.equal(span._span.ended, true) 225 | t.end() 226 | })) 227 | 228 | test('#finish(finishTime) - transaction', setup(function (t) { 229 | const startTime = Date.now() - 1000 230 | const finishTime = startTime + 2000.123 231 | 232 | const tracer = new Tracer(getAgent()) 233 | const span = tracer.startSpan('foo', { startTime }) 234 | 235 | span.finish(finishTime) 236 | 237 | t.equal(span._span.timestamp, startTime * 1000) 238 | t.equal(span._span._timer.duration, 2000.123) 239 | t.equal(span._span.duration(), 2000.123) 240 | 241 | t.end() 242 | })) 243 | 244 | test('#finish() - span', setup(function (t) { 245 | const tracer = new Tracer(getAgent()) 246 | tracer.startSpan('foo') 247 | const span = tracer.startSpan('bar') 248 | t.equal(span._span.ended, false) 249 | span.finish() 250 | t.equal(span._span.ended, true) 251 | t.end() 252 | })) 253 | 254 | test('#finish(finishTime) - span', setup(function (t) { 255 | const startTime = Date.now() - 1000 256 | const finishTime = startTime + 2000.123 257 | 258 | const tracer = new Tracer(getAgent()) 259 | tracer.startSpan('foo') 260 | const span = tracer.startSpan('bar', { startTime }) 261 | 262 | span.finish(finishTime) 263 | 264 | t.equal(span._span.timestamp, startTime * 1000) 265 | t.equal(span._span._timer.duration, 2000.123) 266 | t.equal(span._span.duration(), 2000.123) 267 | 268 | t.end() 269 | })) 270 | -------------------------------------------------------------------------------- /test/tracer.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const opentracing = require('opentracing') 4 | const test = require('tape') 5 | 6 | const { setup, getAgent } = require('./utils') 7 | const Tracer = require('..') 8 | const SpanContext = require('../lib/span_context') 9 | const UnsampledSpan = require('../lib/unsampled_span') 10 | 11 | test('should throw if not given an agent', setup(function (t) { 12 | t.throws(function () { 13 | new Tracer() // eslint-disable-line no-new 14 | }) 15 | t.end() 16 | })) 17 | 18 | test('should use Agent instance given as argument', setup(function (t) { 19 | const agent = getAgent() 20 | const tracer = new Tracer(agent) 21 | 22 | t.equal(tracer._agent, agent) 23 | t.end() 24 | })) 25 | 26 | test('#startSpan()', setup(function (t) { 27 | const tracer = new Tracer(getAgent()) 28 | const span1 = tracer.startSpan() 29 | 30 | t.ok(span1, 'should return span') 31 | t.ok(span1._span, 'should hold reference to span/transaction') 32 | t.equal(span1._span.name, 'unnamed', 'should fall back to default name') 33 | t.equal(span1._span.type, 'custom', 'should fall back to default type') 34 | t.equal(span1._span.sampled, true) 35 | 36 | const span2 = tracer.startSpan() 37 | 38 | t.equal(span1._isTransaction, true, 'first span should be a transaction') 39 | t.equal(span2._isTransaction, false, 'second span should not be a transaction') 40 | 41 | t.end() 42 | })) 43 | 44 | test('#startSpan(name)', setup(function (t) { 45 | const tracer = new Tracer(getAgent()) 46 | const span = tracer.startSpan('foo') 47 | 48 | t.equal(span._span.name, 'foo', 'should use given name') 49 | t.equal(span._span.type, 'custom', 'should fall back to default type') 50 | t.end() 51 | })) 52 | 53 | test('#startSpan(name, {tags: {}})', setup(function (t) { 54 | const tracer = new Tracer(getAgent()) 55 | const span = tracer.startSpan('foo', { tags: {} }) 56 | 57 | t.equal(span._span.name, 'foo', 'should use given name') 58 | t.equal(span._span.type, 'custom', 'should fall back to default type') 59 | t.end() 60 | })) 61 | 62 | test('#startSpan(name, {tags: {type}})', setup(function (t) { 63 | const tracer = new Tracer(getAgent()) 64 | const span = tracer.startSpan('foo', { tags: { type: 'bar' } }) 65 | 66 | t.equal(span._span.name, 'foo', 'should use given name') 67 | t.equal(span._span.type, 'bar', 'should use given type') 68 | t.end() 69 | })) 70 | 71 | test('#startSpan(name, {tags: {...}})', setup(function (t) { 72 | const opts = { tags: { 73 | type: 'bar', 74 | a: '1', 75 | 'a.b': '2', 76 | 'a"b': '3', 77 | 'a*b': '4' 78 | } } 79 | 80 | const tracer = new Tracer(getAgent()) 81 | const span = tracer.startSpan('foo', opts) 82 | 83 | t.equal(span._span.name, 'foo', 'should use given name') 84 | t.equal(span._span.type, 'bar', 'should use given type') 85 | 86 | t.deepEqual(span._span._labels, { 87 | a: '1', 88 | a_b: '4' 89 | }, 'should set expected tags') 90 | 91 | t.deepEqual(opts, { tags: { 92 | type: 'bar', 93 | a: '1', 94 | 'a.b': '2', 95 | 'a"b': '3', 96 | 'a*b': '4' 97 | } }, 'should not mutate input') 98 | 99 | t.end() 100 | })) 101 | 102 | test('#startSpan(name, {startTime})', setup(function (t) { 103 | const startTime = Date.now() - 1000 104 | 105 | const tracer = new Tracer(getAgent()) 106 | const span = tracer.startSpan('foo', { startTime }) 107 | 108 | t.equal(span._span.timestamp, startTime * 1000) 109 | t.end() 110 | })) 111 | 112 | test('#startSpan() - implicit children', setup(function (t) { 113 | const tracer = new Tracer(getAgent()) 114 | const span1 = tracer.startSpan('foo') 115 | const span2 = tracer.startSpan('bar') // implicit child of span1, because span1 is a transaction 116 | const span3 = tracer.startSpan('baz') // implicit child of span1, because span1 is a transaction 117 | 118 | t.equal(span1._isTransaction, true) 119 | t.equal(span2._isTransaction, false) 120 | t.equal(span3._isTransaction, false) 121 | 122 | const _span1 = span1.context()._context 123 | const _span2 = span2.context()._context 124 | const _span3 = span3.context()._context 125 | 126 | t.ok(typeof _span1.traceId, 'string') 127 | t.ok(typeof _span1.id, 'string') 128 | t.equal(_span1.sampled, true) 129 | 130 | // span1 should be the root 131 | t.equal(_span1.parentId, undefined) 132 | 133 | // span2 should be a child of span1 134 | t.equal(_span2.traceId, _span1.traceId, 'span 2 should have expected traceId') 135 | t.notEqual(_span2.id, _span1.id, 'span 2 should have expected id') 136 | t.equal(_span2.parentId, _span1.id, 'span 2 should have expected parentId') 137 | t.equal(_span2.sampled, _span1.sampled, 'span 2 should have expected sampled flag') 138 | 139 | // span3 should be a child of span1 140 | t.equal(_span3.traceId, _span1.traceId, 'span 3 should have expected traceId') 141 | t.notEqual(_span3.id, _span1.id, 'span 3 should have expected id') 142 | t.equal(_span3.parentId, _span1.id, 'span 3 should have expected parentId') 143 | t.equal(_span3.sampled, _span1.sampled, 'span 3 should have expected sampled flag') 144 | 145 | t.end() 146 | })) 147 | 148 | test('#startSpan(name, {childOf})', setup(function (t) { 149 | const tracer = new Tracer(getAgent()) 150 | const span1 = tracer.startSpan('foo') 151 | const span2 = tracer.startSpan('bar') // implicit child of span1, because span1 is a transaction 152 | const span3 = tracer.startSpan('baz', { childOf: span2.context() }) 153 | 154 | t.equal(span1._isTransaction, true) 155 | t.equal(span2._isTransaction, false) 156 | t.equal(span3._isTransaction, false) 157 | 158 | const _span1 = span1.context()._context 159 | const _span2 = span2.context()._context 160 | const _span3 = span3.context()._context 161 | 162 | t.ok(typeof _span1.traceId, 'string') 163 | t.ok(typeof _span1.id, 'string') 164 | t.equal(_span1.sampled, true) 165 | 166 | // span1 should be the root 167 | t.equal(_span1.parentId, undefined) 168 | 169 | // span2 should be a child of span1 170 | t.equal(_span2.traceId, _span1.traceId, 'span 2 should have expected traceId') 171 | t.notEqual(_span2.id, _span1.id, 'span 2 should have expected id') 172 | t.equal(_span2.parentId, _span1.id, 'span 2 should have expected parentId') 173 | t.equal(_span2.sampled, _span1.sampled, 'span 2 should have expected sampled flag') 174 | 175 | // span3 should be a child of span2 176 | t.equal(_span3.traceId, _span2.traceId, 'span 3 should have expected traceId') 177 | t.notEqual(_span3.id, _span2.id, 'span 3 should have expected id') 178 | t.equal(_span3.parentId, _span2.id, 'span 3 should have expected parentId') 179 | t.equal(_span3.sampled, _span2.sampled, 'span 3 should have expected sampled flag') 180 | 181 | t.end() 182 | })) 183 | 184 | test('#startSpan(name, {references: [childOf]})', setup(function (t) { 185 | const tracer = new Tracer(getAgent()) 186 | const span1 = tracer.startSpan('foo') 187 | const span2 = tracer.startSpan('bar') // implicit child of span1, because span1 is a transaction 188 | const references = [ 189 | new opentracing.Reference(opentracing.REFERENCE_CHILD_OF, span2.context()) 190 | ] 191 | const span3 = tracer.startSpan('baz', { references }) 192 | 193 | t.equal(span1._isTransaction, true) 194 | t.equal(span2._isTransaction, false) 195 | t.equal(span3._isTransaction, false) 196 | 197 | const _span1 = span1.context()._context 198 | const _span2 = span2.context()._context 199 | const _span3 = span3.context()._context 200 | 201 | t.ok(typeof _span1.traceId, 'string') 202 | t.ok(typeof _span1.id, 'string') 203 | t.equal(_span1.sampled, true) 204 | 205 | // span1 should be the root 206 | t.equal(_span1.parentId, undefined) 207 | 208 | // span2 should be a child of span1 209 | t.equal(_span2.traceId, _span1.traceId, 'span 2 should have expected traceId') 210 | t.notEqual(_span2.id, _span1.id, 'span 2 should have expected id') 211 | t.equal(_span2.parentId, _span1.id, 'span 2 should have expected parentId') 212 | t.equal(_span2.sampled, _span1.sampled, 'span 2 should have expected sampled flag') 213 | 214 | // span3 should be a child of span2 215 | t.equal(_span3.traceId, _span2.traceId, 'span 3 should have expected traceId') 216 | t.notEqual(_span3.id, _span2.id, 'span 3 should have expected id') 217 | t.equal(_span3.parentId, _span2.id, 'span 3 should have expected parentId') 218 | t.equal(_span3.sampled, _span2.sampled, 'span 3 should have expected sampled flag') 219 | 220 | t.end() 221 | })) 222 | 223 | // This currently doesn't behave in a logical way as when the followsFrom 224 | // reference is being ignored, the agent will simply automatically associate 225 | // span2 with span1, because span1 is a transaction 226 | test.skip('#startSpan(name, {references: [followsFrom]})', setup(function (t) { 227 | const tracer = new Tracer(getAgent()) 228 | const span1 = tracer.startSpan('foo') 229 | const references = [ 230 | new opentracing.Reference(opentracing.REFERENCE_FOLLOWS_FROM, span1.context()) 231 | ] 232 | const span2 = tracer.startSpan('bar', { references }) 233 | 234 | const _span1 = span1.context()._context 235 | const _span2 = span2.context()._context 236 | 237 | t.notEqual(_span1.traceId, _span1.traceId) 238 | t.notEqual(_span1.id, _span1.id) 239 | t.equal(_span2.parentId, undefined) 240 | t.equal(_span1.parentId, undefined) 241 | t.end() 242 | })) 243 | 244 | test('#startSpan(name, {references: [followsFrom, childOf, childOf]})', setup(function (t) { 245 | const tracer = new Tracer(getAgent()) 246 | const span1 = tracer.startSpan('foo') 247 | const span2 = tracer.startSpan('bar') // implicit child of span1, because span1 is a transaction 248 | const references = [ 249 | new opentracing.Reference(opentracing.REFERENCE_FOLLOWS_FROM, span1.context()), 250 | new opentracing.Reference(opentracing.REFERENCE_CHILD_OF, span2.context()), 251 | new opentracing.Reference(opentracing.REFERENCE_CHILD_OF, span1.context()) 252 | ] 253 | const span3 = tracer.startSpan('baz', { references }) 254 | 255 | t.equal(span1._isTransaction, true) 256 | t.equal(span2._isTransaction, false) 257 | t.equal(span3._isTransaction, false) 258 | 259 | const _span1 = span1.context()._context 260 | const _span2 = span2.context()._context 261 | const _span3 = span3.context()._context 262 | 263 | t.ok(typeof _span1.traceId, 'string') 264 | t.ok(typeof _span1.id, 'string') 265 | t.equal(_span1.sampled, true) 266 | 267 | // span1 should be the root 268 | t.equal(_span1.parentId, undefined) 269 | 270 | // span2 should be a child of span1 271 | t.equal(_span2.traceId, _span1.traceId, 'span 2 should have expected traceId') 272 | t.notEqual(_span2.id, _span1.id, 'span 2 should have expected id') 273 | t.equal(_span2.parentId, _span1.id, 'span 2 should have expected parentId') 274 | t.equal(_span2.sampled, _span1.sampled, 'span 2 should have expected sampled flag') 275 | 276 | // span3 should be a child of span2 277 | t.equal(_span3.traceId, _span2.traceId, 'span 3 should have expected traceId') 278 | t.notEqual(_span3.id, _span2.id, 'span 3 should have expected id') 279 | t.equal(_span3.parentId, _span2.id, 'span 3 should have expected parentId') 280 | t.equal(_span3.sampled, _span2.sampled, 'span 3 should have expected sampled flag') 281 | 282 | t.end() 283 | })) 284 | 285 | test('#startSpan() - ended transaction', setup(function (t) { 286 | const tracer = new Tracer(getAgent()) 287 | 288 | const span1 = tracer.startSpan('foo') 289 | span1.finish() 290 | 291 | const span2 = tracer.startSpan('bar') 292 | 293 | t.equal(span1._isTransaction, true) 294 | t.equal(span2._isTransaction, true) 295 | t.equal(span1.context()._context.parentId, undefined) 296 | t.equal(span2.context()._context.parentId, undefined) 297 | t.end() 298 | })) 299 | 300 | test('#startSpan() - not sampled', setup(function (t) { 301 | const agent = getAgent() 302 | agent._conf.transactionSampleRate = 0 303 | 304 | const tracer = new Tracer(agent) 305 | const span1 = tracer.startSpan() 306 | 307 | t.ok(span1, 'should return span') 308 | t.ok(span1._span, 'should hold reference to span/transaction') 309 | t.equal(span1._isTransaction, true, 'first span should be a transaction') 310 | t.equal(span1._span.sampled, false) 311 | 312 | const span2 = tracer.startSpan() 313 | 314 | t.ok(span2 instanceof UnsampledSpan) 315 | 316 | agent._conf.transactionSampleRate = 1 317 | 318 | t.end() 319 | })) 320 | 321 | test('#inject(span, http, undefined)', setup(function (t) { 322 | const tracer = new Tracer(getAgent()) 323 | const span = tracer.startSpan('foo') 324 | // TODO: Is this expected? 325 | t.throws(function () { 326 | tracer.inject(span, opentracing.FORMAT_HTTP_HEADERS) 327 | }) 328 | t.end() 329 | })) 330 | 331 | test('#inject(span, http, {})', setup(function (t) { 332 | const tracer = new Tracer(getAgent()) 333 | const span = tracer.startSpan('foo') 334 | const carrier = {} 335 | tracer.inject(span, opentracing.FORMAT_HTTP_HEADERS, carrier) 336 | t.equal(carrier['elastic-apm-traceparent'], span.context().toString()) 337 | t.end() 338 | })) 339 | 340 | test('#inject(context, http, {})', setup(function (t) { 341 | const tracer = new Tracer(getAgent()) 342 | const span = tracer.startSpan('foo') 343 | const carrier = {} 344 | tracer.inject(span.context(), opentracing.FORMAT_HTTP_HEADERS, carrier) 345 | t.equal(carrier['elastic-apm-traceparent'], span.context().toString()) 346 | t.end() 347 | })) 348 | 349 | test('#inject(noop, http, {})', setup(function (t) { 350 | const agent = getAgent() 351 | agent._conf.transactionSampleRate = 0 352 | 353 | const tracer = new Tracer(agent) 354 | 355 | const span1 = tracer.startSpan('foo') 356 | t.equal(span1._isTransaction, true) 357 | t.equal(span1._span.sampled, false) 358 | 359 | const span2 = tracer.startSpan('foo') 360 | t.ok(span2 instanceof UnsampledSpan) 361 | 362 | const carrier = {} 363 | 364 | tracer.inject(span2, opentracing.FORMAT_HTTP_HEADERS, carrier) 365 | 366 | t.equal(carrier['elastic-apm-traceparent'], span1.context().toString()) 367 | 368 | agent._conf.transactionSampleRate = 1 369 | 370 | t.end() 371 | })) 372 | 373 | test('#extract(http, undefined)', setup(function (t) { 374 | const tracer = new Tracer(getAgent()) 375 | const context = tracer.extract(opentracing.FORMAT_HTTP_HEADERS) 376 | t.equal(context, null) 377 | t.end() 378 | })) 379 | 380 | test('#extract(http, {})', setup(function (t) { 381 | const tracer = new Tracer(getAgent()) 382 | const context = tracer.extract(opentracing.FORMAT_HTTP_HEADERS, {}) 383 | t.equal(context, null) 384 | t.end() 385 | })) 386 | 387 | test('#extract(http, {elastic-apm-traceparent: null})', setup(function (t) { 388 | const tracer = new Tracer(getAgent()) 389 | const context = tracer.extract(opentracing.FORMAT_HTTP_HEADERS, { 390 | 'elastic-apm-traceparent': null 391 | }) 392 | t.equal(context, null) 393 | t.end() 394 | })) 395 | 396 | // TODO: Currently the header string isn't validated. This might not be an issue though 397 | test.skip('#extract(http, {elastic-apm-traceparent: invalid})', setup(function (t) { 398 | const tracer = new Tracer(getAgent()) 399 | const context = tracer.extract(opentracing.FORMAT_HTTP_HEADERS, { 400 | 'elastic-apm-traceparent': 'invalid' 401 | }) 402 | t.equal(context, null) 403 | t.end() 404 | })) 405 | 406 | test('#extract(http, {elastic-apm-traceparent: valid})', setup(function (t) { 407 | const tracer = new Tracer(getAgent()) 408 | const context = tracer.extract(opentracing.FORMAT_HTTP_HEADERS, { 409 | 'elastic-apm-traceparent': '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' 410 | }) 411 | t.ok(context instanceof SpanContext) 412 | t.equal(context.toString(), '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') 413 | t.end() 414 | })) 415 | -------------------------------------------------------------------------------- /test/utils/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const agent = require('elastic-apm-node').start({ 4 | captureExceptions: false, 5 | centralConfig: false, 6 | metricsInterval: 0 7 | }) 8 | 9 | exports.setup = setup 10 | exports.getAgent = getAgent 11 | 12 | function getAgent (conf = {}) { 13 | return agent 14 | } 15 | 16 | function setup (runTest) { 17 | return function (t) { 18 | t.on('end', clean) 19 | runTest(t) 20 | } 21 | } 22 | 23 | function clean () { 24 | agent._instrumentation.currentTransaction = null 25 | } 26 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["lib/**/*"], 3 | "compilerOptions": { 4 | "allowJs": true, 5 | "declaration": true, 6 | "emitDeclarationOnly": true, 7 | "outFile": "types.d.ts" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /types.d.ts: -------------------------------------------------------------------------------- 1 | declare module "span" { 2 | export = Span; 3 | class Span { 4 | constructor(tracer: any, span: any); 5 | __tracer: any; 6 | __context: SpanContext; 7 | _span: any; 8 | _isTransaction: boolean; 9 | _context(): SpanContext; 10 | _tracer(): any; 11 | _setOperationName(name: any): void; 12 | addTags(tags: any): Span; 13 | _addTags(tags: any): void; 14 | _log(logs: any, timestamp: any): void; 15 | _finish(finishTime: any): void; 16 | } 17 | import SpanContext = require("span_context"); 18 | } 19 | declare module "span_context" { 20 | export = SpanContext; 21 | class SpanContext { 22 | constructor(context: any); 23 | _context: any; 24 | toString(): any; 25 | } 26 | } 27 | declare module "tracer" { 28 | export = Tracer; 29 | class Tracer { 30 | constructor(agent: any); 31 | _agent: any; 32 | _startSpan(name: any, opts: any): any; 33 | _inject(spanContext: any, format: any, carrier: any): void; 34 | _extract(format: any, carrier: any): SpanContext; 35 | } 36 | import SpanContext = require("span_context"); 37 | } 38 | declare module "unsampled_span" { 39 | export = UnsampledSpan; 40 | class UnsampledSpan { 41 | constructor(elasticTransaction: any); 42 | __context: SpanContext; 43 | _elasticTransaction: any; 44 | _isTransaction: boolean; 45 | _context(): SpanContext; 46 | } 47 | import SpanContext = require("span_context"); 48 | } 49 | --------------------------------------------------------------------------------