├── .circleci └── config.yml ├── .eslintignore ├── .eslintrc.js ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ └── feature_request.md ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── LICENSE-3rdparty.csv ├── NOTICE ├── README.md ├── eslint.config.js ├── package.json ├── scripts ├── color.js ├── exec.js ├── release.js └── version-update.js ├── src ├── datadog.ts ├── datadogProbabilitySampler.ts ├── datadogPropagator.ts ├── datadogSpanProcessor.ts ├── defaults.ts ├── index.ts ├── transform.ts ├── types.ts └── version.ts ├── test ├── datadog.test.ts ├── datadogProbabilitySampler.test.ts ├── datadogPropagator.test.ts ├── datadogSpanProcessor.test.ts ├── mocks.ts └── transform.test.ts └── tsconfig.json /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | node_test_env: &node_test_env 4 | NPM_CONFIG_UNSAFE_PERM: true 5 | 6 | node_unit_tests: &node_unit_tests 7 | steps: 8 | - checkout 9 | - run: 10 | name: Install Root Dependencies 11 | command: npm install --ignore-scripts 12 | - run: 13 | name: Unit tests 14 | command: npm run test 15 | 16 | jobs: 17 | node8: 18 | docker: 19 | - image: node:8 20 | environment: *node_test_env 21 | <<: *node_unit_tests 22 | node10: 23 | docker: 24 | - image: node:10 25 | environment: *node_test_env 26 | <<: *node_unit_tests 27 | node12: 28 | docker: 29 | - image: node:12 30 | environment: *node_test_env 31 | <<: *node_unit_tests 32 | node14: 33 | docker: 34 | - image: node:14 35 | environment: *node_test_env 36 | <<: *node_unit_tests 37 | 38 | workflows: 39 | version: 2 40 | build: 41 | jobs: 42 | - node8 43 | - node10 44 | - node12 45 | - node14 46 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "env": { 3 | "mocha": true, 4 | "node": true 5 | }, 6 | ...require('./eslint.config.js') 7 | } 8 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the f 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # Bower dependency directory (https://bower.io/) 24 | bower_components 25 | 26 | # node-waf configuration 27 | .lock-wscript 28 | 29 | # Compiled binary addons (https://nodejs.org/api/addons.html) 30 | build/Release 31 | 32 | # Dependency directories 33 | node_modules/ 34 | jspm_packages/ 35 | build/ 36 | 37 | # TypeScript v1 declaration files 38 | typings/ 39 | 40 | # Optional npm cache directory 41 | .npm 42 | 43 | # Optional eslint cache 44 | .eslintcache 45 | 46 | # Optional REPL history 47 | .node_repl_history 48 | 49 | # Output of 'npm pack' 50 | *.tgz 51 | 52 | # Yarn Integrity file 53 | .yarn-integrity 54 | 55 | # dotenv environment variables file 56 | .env 57 | 58 | # next.js build output 59 | .next 60 | 61 | # lock files 62 | yarn.lock 63 | package-lock.json 64 | packages/**/yarn.lock 65 | packages/**/package-lock.json 66 | 67 | # docs files 68 | docs 69 | 70 | .nyc_output 71 | 72 | #lerna 73 | .changelog 74 | package.json.lerna_backup 75 | 76 | # OS generated files 77 | .DS_Store 78 | 79 | # VsCode configs 80 | .vscode/ 81 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Release History: opentelemetry-exporter-datadog 2 | 3 | ## [Unreleased] 4 | ### Fixed 5 | - update link in deprecation note 6 | 7 | ## [0.2.0] - 2020-02-11 8 | ### Fixed 9 | - documentation updates 10 | 11 | ### Added 12 | - support for opentelemetry-js v0.16.0 13 | - add resource attributes as span tags 14 | 15 | ## [0.1.2] - 2020-07-30 16 | ### Fixed 17 | - fix filtering of internal requests to trace agent 18 | 19 | ## [0.1.1] - 2020-07-22 20 | ### Fixed 21 | - fix readme 22 | - add changelog 23 | 24 | ## [0.1.0] - 2020-07-22 25 | ### Added 26 | - initial release 27 | - add DatadogSpanProcessor 28 | - add DatadogExporter 29 | - add DatadogProbabilitySampler 30 | - add DatadogPropagator 31 | - add setup and usage instructions 32 | - add unit tests -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Community contributions to the Datadog Opentelemetry Exporter library for JS are welcome! See below for some basic guidelines. 4 | 5 | ## Want to request a new feature? 6 | 7 | Many great ideas for new features come from the community, and we'd be happy to consider yours! 8 | 9 | To share your request, you can [open a Github issue](https://github.com/DataDog/dd-opentelemetry-exporter-js/issues/new) with the details about what you'd like to see. At a minimum, please provide: 10 | 11 | - The goal of the new feature 12 | - A description of how it might be used or behave 13 | - Links to any important resources (e.g. Github repos, websites, screenshots, specifications, diagrams) 14 | 15 | Additionally, if you can, include: 16 | 17 | - A description of how it could be accomplished 18 | - Code snippets that might demonstrate its use or implementation 19 | - Screenshots or mockups that visually demonstrate the feature 20 | - Links to similar features that would serve as a good comparison 21 | - (Any other details that would be useful for implementing this feature!) 22 | 23 | 24 | ## Found a bug? 25 | 26 | For any urgent matters (such as outages) or issues concerning the Datadog service or UI, contact our support team via https://docs.datadoghq.com/help/ for direct, faster assistance. 27 | 28 | You may submit bug reports concerning the Datadog OpenTelemetry Exporter for JS by [opening a Github issue](https://github.com/DataDog/dd-opentelemetry-exporter-js/issues/new). At a minimum, please provide: 29 | 30 | - A description of the problem 31 | - Steps to reproduce 32 | - Expected behavior 33 | - Actual behavior 34 | - Errors (with stack traces) or warnings received 35 | - Any details you can share about your configuration including: 36 | - Node version & platform 37 | - `opentelemetry-exporter-datadog` version 38 | - Versions of any other relevant packages (or a `package.json` if available) 39 | - Any configuration settings for this library and opentelemetry-js trace library 40 | 41 | If at all possible, also provide: 42 | 43 | - Logs (from the tracer/application/agent) or other diagnostics 44 | - Screenshots, links, or other visual aids that are publicly accessible 45 | - Code sample or test that reproduces the problem 46 | - An explanation of what causes the bug and/or how it can be fixed 47 | 48 | Reports that include rich detail are better, and ones with code that reproduce the bug are best. 49 | 50 | ## Have a patch? 51 | 52 | We welcome code contributions to the library, which you can [submit as a pull request](https://github.com/DataDog/dd-opentelemetry-exporter-js/pull/new/master). To create a pull request: 53 | 54 | 1. **Fork the repository** from https://github.com/DataDog/dd-opentelemetry-exporter-js 55 | 2. **Make any changes** for your patch. 56 | 3. **Write tests** that demonstrate how the feature works or how the bug is fixed. 57 | 4. **Update any documentation** such as `README.md`, especially for new features. 58 | 5. **Submit the pull request** from your fork back to https://github.com/DataDog/dd-opentelemetry-exporter-js. Bugs should merge back to `master`. 59 | 60 | The pull request will be run through our CI pipeline, and a project member will review the changes with you. At a minimum, to be accepted and merged, pull requests must: 61 | 62 | - Have a stated goal and detailed description of the changes made 63 | - Include thorough test coverage and documentation, where applicable 64 | - Pass all tests and code quality checks (linting/coverage/benchmarks) on CI 65 | - Receive at least one approval from a project member with push permissions 66 | 67 | We also recommend that you share in your description: 68 | 69 | - Any motivations or intent for the contribution 70 | - Links to any issues/pull requests it might be related to 71 | - Links to any webpages or other external resources that might be related to the change 72 | - Screenshots, code samples, or other visual aids that demonstrate the changes or how they are implemented 73 | - Benchmarks if the feature is anticipated to have performance implications 74 | - Any limitations, constraints or risks that are important to consider 75 | 76 | 77 | ## Final word 78 | 79 | Many thanks to all of our contributors, and looking forward to seeing you on Github! :tada: 80 | 81 | - Datadog JS APM Team 82 | -------------------------------------------------------------------------------- /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 2020 OpenTelemetry Authors 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 | -------------------------------------------------------------------------------- /LICENSE-3rdparty.csv: -------------------------------------------------------------------------------- 1 | Component,Origin,License,Copyright 2 | require,@opentelemetry/api,Apache-2.0,Copyright 2020 OpenTelemetry Authors 3 | require,@opentelemetry/core,Apache-2.0,Copyright 2020 OpenTelemetry Authors 4 | require,@opentelemetry/resources,Apache-2.0,Copyright 2020 OpenTelemetry Authors 5 | require,@opentelemetry/tracing,Apache-2.0,Copyright 2020 OpenTelemetry Authors 6 | dev,@opentelemetry/resources,Apache-2.0,Copyright 2020 OpenTelemetry Authors 7 | dev,@types/mocha,MIT,Copyright Authors 8 | dev,@types/node,MIT,Copyright Authors 9 | dev,@types/sinon,MIT,Copyright Authors 10 | dev,@typescript-eslint/eslint-plugin,MIT,Copyright JS Foundation and other contributors https://js.foundation 11 | dev,@typescript-eslint/parse,MIT,Copyright JS Foundation and other contributors https://js.foundation 12 | dev,benchmark,MIT,Copyright 2010-2016 Mathias Bynens Robert Kieffer John-David Dalton 13 | dev,codecov,MIT,Copyright 2014 Gregg Caines 14 | dev,eslint,MIT,Copyright JS Foundation and other contributors https://js.foundation 15 | dev,eslint-config-airbnb-base,MIT,Copyright (c) 2012 Airbnb 16 | dev,eslint-plugin-header,MIT,Stuart Knightley 17 | dev,eslint-plugin-import,MIT,Copyright 2015 Ben Mosher 18 | dev,gts,Apache-2.0,Copyright 2018 Google Inc. 19 | dev,husky,MIT,Copyright (c) 2017 20 | dev,mocha,MIT,Copyright 2011-2018 JS Foundation and contributors https://js.foundation 21 | dev,nock,MIT,Copyright 2017 Pedro Teixeira and other contributors 22 | dev,nyc,ISC,Copyright 2015 Contributors 23 | dev,rimraf,ISC,Copyright Isaac Z. Schlueter and Contributors 24 | dev,sinon,BSD-3-Clause,Copyright 2010-2017 Christian Johansen 25 | dev,ts-mocha,MIT,Copyright (c) 2016-2018 Piotr Witek 26 | dev,ts-node,MIT,Copyright (c) 2014 Blake Embrey 27 | dev,typescript,Apache-2.0,Copyright (c) Microsoft Corporation 28 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Datadog dd-opentelemetry-exporter-js 2 | Copyright [2020] Datadog, Inc. 3 | 4 | This product includes software developed at Datadog (https://www.datadoghq.com/). -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dd-opentelemetry-exporter-js 2 | 3 | *Note*: This Repository has been deprecated and is no longer actively maintained. Please refer to [OTLP Ingest in Datadog Agent](https://docs.datadoghq.com/tracing/setup_overview/open_standards/#otlp-ingest-in-datadog-agent) for support options for using OpenTelemetry and Datadog. 4 | 5 | ## OpenTelemetry Datadog Span Exporter 6 | 7 | **[DEPRECATED]** 8 | 9 | [![Apache License][license-image]][license-image] 10 | 11 | OpenTelemetry Datadog Trace Exporter allows the user to send collected traces to a Datadog Trace-Agent. 12 | 13 | [Datadog APM](https://www.datadoghq.com), is a distributed tracing system. It is used for monitoring and troubleshooting microservices-based distributed systems. 14 | 15 | ## Prerequisites 16 | 17 | The OpenTelemetry Datadog Trace Exporter requires a Datadog Agent that it can send exported traces to. This Agent then forwards those traces to a Datadog API intake endpoint. To get up and running with Datadog in your environment follow the Getting Started Instructions for Installing and configuring a [Datadog Agent](https://docs.datadoghq.com/tracing/#1-configure-the-datadog-agenthttps://docs.datadoghq.com/tracing/#1-configure-the-datadog-agent) which the exporter can send traces to. By default, the Agent listens for Traces at `localhost:8126`. 18 | 19 | ## Installation 20 | 21 | To install: 22 | 23 | ```bash 24 | npm install --save opentelemetry-exporter-datadog 25 | ``` 26 | 27 | ## Usage 28 | 29 | Install the datadog processor and datadog exporter on your application and pass the options. It should contain a service name (default is `dd-service`). 30 | 31 | Furthermore, the `agentUrl` option (which defaults to `http://localhost:8126`), can instead be set by the 32 | `DD_TRACE_AGENT_URL` environment variable to reduce in-code config. If both are 33 | set, the value set by the option in code is authoritative. 34 | 35 | ```js 36 | import { NodeTracerProvider } from '@opentelemetry/node'; 37 | import { DatadogSpanProcessor, DatadogExporter, DatadogPropagator, DatadogProbabilitySampler } from 'opentelemetry-exporter-datadog'; 38 | 39 | const provider = new NodeTracerProvider(); 40 | 41 | const exporterOptions = { 42 | serviceName: 'my-service', // optional 43 | agentUrl: 'http://localhost:8126', // optional 44 | tags: 'example_key:example_value,example_key_two:value_two', // optional 45 | env: 'production', // optional 46 | version: '1.0' // optional 47 | } 48 | 49 | const exporter = new DatadogExporter(exporterOptions); 50 | 51 | // Now, register the exporter. 52 | 53 | provider.addSpanProcessor(new DatadogSpanProcessor(exporter)); 54 | 55 | // Next, add the Datadog Propagator for distributed tracing 56 | 57 | provider.register({ 58 | propagator: new DatadogPropagator(), 59 | // while datadog suggests the default ALWAYS_ON sampling, for probability sampling, 60 | // to ensure the appropriate generation of tracing metrics by the datadog-agent, 61 | // use the `DatadogProbabilitySampler` 62 | // sampler: new DatadogProbabilitySampler(0.75) 63 | }) 64 | ``` 65 | 66 | It's recommended to use the `DatadogSpanProcessor` 67 | 68 | - `DatadogSpanProcessor`: The implementation of `SpanProcessor` that passes ended complete traces to the configured `SpanExporter`. 69 | 70 | ## Probability Based Sampling Setup 71 | 72 | - By default, the OpenTelemetry tracer will sample and record all spans. This default is the suggest sampling approach to take when exporting to Datadog. However, if you wish to use Probability Based sampling, we recommend that, in order for the Datadog trace-agent to collect trace related metrics effectively, to use the `DatadogProbabilitySampler`. You can enabled Datadog Probability based sampling with the code snippet below when registering your tracer provider. 73 | 74 | ```js 75 | provider.register({ 76 | // while datadog suggests the default ALWAYS_ON sampling, for probability sampling, 77 | // to ensure the appropriate generation of tracing metrics by the datadog-agent, 78 | // use the `DatadogProbabilitySampler` 79 | sampler: new DatadogProbabilitySampler(0.75) 80 | }) 81 | ``` 82 | 83 | ## Distributed Tracing Context Propagation 84 | 85 | - In order to connect your OpenTelemetry Instrumentation Application with other Datadog Instrumented Applications, you must propagate the distribute tracing context with Datadog specific headers. To accomplish this we recommend configuring to use `DatadogPropagator`. You can enabled Datadog Propagation with the below code snippet below when registering your tracer provider. 86 | 87 | ```js 88 | provider.register({ 89 | propagator: new DatadogPropagator(), 90 | }) 91 | ``` 92 | 93 | - To propagator multiple header formats to downstream application, use a `CompositePropogator`. For example, to use both B3 and Datadog formatted distributed tracing headers for Propagation, you can enable a Composite Propagator with the below code snippet when registering your tracer provider. 94 | 95 | ```js 96 | import { CompositePropagator, B3Propagator } from '@opentelemetry/core'; 97 | import { DatadogPropagator } from '@opentelemetry/exporter-datadog'; 98 | 99 | const provider = new NodeTracerProvider(); 100 | // ... provider setup with appropriate exporter 101 | 102 | provider.register({ 103 | propagator: new CompositePropagator({ 104 | propagators: [new B3Propagator(), new DatadogPropagator()] 105 | }), 106 | }); 107 | ``` 108 | 109 | ## Configuration Options 110 | 111 | ### Configuration Options - Datadog Agent URL 112 | 113 | By default the OpenTelemetry Datadog Exporter transmits traces to `http://localhost:8126`. You can configure the application to send traces to a diffent URL using the following environmennt variables: 114 | 115 | - `DD_TRACE_AGENT_URL`: The `: 155 | - For more information on OpenTelemetry, visit: 156 | - For more about OpenTelemetry JavaScript: 157 | - Learn more about OpenTelemetry on [gitter][gitter-url] 158 | 159 | ## License 160 | 161 | Apache 2.0 - See [LICENSE][license-url] for more information. 162 | 163 | [gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg 164 | [gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge 165 | [license-url]: https://github.com/DatadDog/dd-opentelemetry-exporter-js/blob/master/LICENSE 166 | [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat 167 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: [ 3 | "@typescript-eslint", 4 | "header" 5 | ], 6 | extends: [ 7 | "./node_modules/gts", 8 | ], 9 | parser: "@typescript-eslint/parser", 10 | parserOptions: { 11 | "project": "./tsconfig.json" 12 | }, 13 | rules: { 14 | "@typescript-eslint/no-this-alias": "off", 15 | "eqeqeq": "off", 16 | "prefer-rest-params": "off", 17 | "@typescript-eslint/naming-convention": [ 18 | "error", 19 | { 20 | "selector": "memberLike", 21 | "modifiers": ["private", "protected"], 22 | "format": ["camelCase"], 23 | "leadingUnderscore": "require" 24 | } 25 | ], 26 | "@typescript-eslint/no-inferrable-types": ["error", { ignoreProperties: true }], 27 | "arrow-parens": ["error", "as-needed"], 28 | "prettier/prettier": ["error", { "singleQuote": true, "arrowParens": "avoid" }], 29 | "node/no-deprecated-api": ["warn"] 30 | }, 31 | overrides: [ 32 | { 33 | "files": ["test/**/*.ts"], 34 | "rules": { 35 | "no-empty": "off", 36 | "@typescript-eslint/ban-ts-ignore": "off", 37 | "@typescript-eslint/no-empty-function": "off", 38 | "@typescript-eslint/no-explicit-any": "off", 39 | "@typescript-eslint/no-unused-vars": "off", 40 | "@typescript-eslint/no-var-requires": "off", 41 | "@typescript-eslint/ban-ts-comment": "off" 42 | } 43 | }, 44 | { 45 | "files": ["src/**/*.ts"], 46 | "rules": { 47 | "@typescript-eslint/no-unused-vars": "off", 48 | "@typescript-eslint/no-explicit-any": "off", 49 | } 50 | } 51 | ] 52 | }; 53 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opentelemetry-exporter-datadog", 3 | "version": "0.2.0", 4 | "description": "OpenTelemetry Exporter Datadog allows user to send collected traces to Datadog", 5 | "main": "build/src/index.js", 6 | "types": "build/src/index.d.ts", 7 | "repository": "Datadog/dd-opentelemetry-exporter-js", 8 | "scripts": { 9 | "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", 10 | "tdd": "npm run test -- --watch-extensions ts --watch", 11 | "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p .", 12 | "clean": "rimraf build/*", 13 | "lint": "eslint . --ext .ts", 14 | "lint:fix": "eslint . --ext .ts --fix", 15 | "precompile": "tsc --version", 16 | "version:update": "node ./scripts/version-update.js", 17 | "compile": "npm run version:update && tsc -p .", 18 | "prepare": "npm run compile", 19 | "watch": "tsc -w" 20 | }, 21 | "keywords": [ 22 | "opentelemetry", 23 | "nodejs", 24 | "tracing", 25 | "profiling", 26 | "datadog" 27 | ], 28 | "author": "Datadog Inc. ", 29 | "license": "Apache-2.0", 30 | "bugs": { 31 | "url": "https://github.com/DataDog/dd-opentelemetry-exporter-js/issues" 32 | }, 33 | "homepage": "https://github.com/DataDog/dd-opentelemetry-exporter-js#readme", 34 | "engines": { 35 | "node": ">=8.0.0" 36 | }, 37 | "files": [ 38 | "build/src/**/*.js", 39 | "build/src/**/*.d.ts", 40 | "doc", 41 | "LICENSE", 42 | "README.md" 43 | ], 44 | "publishConfig": { 45 | "access": "public" 46 | }, 47 | "devDependencies": { 48 | "@types/mocha": "^7.0.0", 49 | "@types/node": "^14.0.5", 50 | "@types/sinon": "^9.0.4", 51 | "@typescript-eslint/eslint-plugin": "3.6.0", 52 | "@typescript-eslint/parser": "3.6.0", 53 | "codecov": "^3.6.1", 54 | "eslint": "7.4.0", 55 | "eslint-config-airbnb-base": "14.2.0", 56 | "eslint-plugin-header": "3.0.0", 57 | "eslint-plugin-import": "2.22.0", 58 | "gts": "^2.0.0", 59 | "husky": "4.2.5", 60 | "mocha": "^7.1.2", 61 | "nock": "12.0.3", 62 | "nyc": "^15.0.0", 63 | "rimraf": "^3.0.0", 64 | "sinon": "^9.0.2", 65 | "ts-mocha": "^7.0.0", 66 | "ts-node": "^8.6.2", 67 | "typescript": "4.1.3" 68 | }, 69 | "dependencies": { 70 | "@opentelemetry/api": "^0.16.0", 71 | "@opentelemetry/core": "^0.16.0", 72 | "@opentelemetry/resources": "^0.16.0", 73 | "@opentelemetry/tracing": "^0.16.0", 74 | "dd-trace": "^0.21.0" 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /scripts/color.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | 'use strict' 9 | 10 | // https://en.wikipedia.org/wiki/ANSI_escape_code#Colors 11 | module.exports = { 12 | GRAY: '\\033[1;90m', 13 | CYAN: '\\033[1;36m', 14 | NONE: '\\033[0m' 15 | } -------------------------------------------------------------------------------- /scripts/exec.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | 'use strict' 9 | 10 | const execSync = require('child_process').execSync 11 | const color = require('./color') 12 | 13 | function exec (command, options) { 14 | options = Object.assign({ stdio: [0, 1, 2] }, options) 15 | 16 | execSync(`echo "${color.GRAY}$ ${command}${color.NONE}"`, { stdio: [0, 1, 2] }) 17 | 18 | return execSync(command, options) 19 | } 20 | 21 | function pipe (command, options) { 22 | return exec(command, Object.assign({ stdio: 'pipe' }, options)) 23 | .toString() 24 | .replace(/\n$/, '') 25 | } 26 | 27 | exec.pipe = pipe 28 | 29 | module.exports = exec -------------------------------------------------------------------------------- /scripts/release.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | 'use strict' 9 | 10 | const exec = require('./exec') 11 | 12 | exec('npm whoami') 13 | exec('git checkout master') 14 | exec('git pull') 15 | 16 | const pkg = require('../package.json') 17 | 18 | exec(`git tag v${pkg.version}`) 19 | exec(`git push origin refs/tags/v${pkg.version}`) 20 | exec('npm publish') -------------------------------------------------------------------------------- /scripts/version-update.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | const fs = require('fs'); 9 | const os = require('os'); 10 | const path = require('path'); 11 | 12 | const appRoot = process.cwd(); 13 | 14 | const packageJsonUrl = path.resolve(`${appRoot}/package.json`); 15 | const pjson = require(packageJsonUrl); 16 | 17 | const content = `/* 18 | * Unless explicitly stated otherwise all files in this repository are licensed 19 | * under the Apache 2.0 license (see LICENSE). 20 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 21 | * Copyright 2020 Datadog, Inc. 22 | */ 23 | 24 | // this is autogenerated file, see scripts/version-update.js 25 | export const VERSION = '${pjson.version}'; 26 | `; 27 | 28 | const fileUrl = path.join(appRoot, "src", "version.ts") 29 | 30 | fs.writeFileSync(fileUrl, content.replace(/\n/g, os.EOL)); 31 | -------------------------------------------------------------------------------- /src/datadog.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import * as api from '@opentelemetry/api'; 9 | import { ExportResult, ExportResultCode } from '@opentelemetry/core'; 10 | import { ReadableSpan, SpanExporter } from '@opentelemetry/tracing'; 11 | import { translateToDatadog } from './transform'; 12 | import { AgentExporter, PrioritySampler, DatadogExporterConfig } from './types'; 13 | import { URL } from 'url'; 14 | import { DatadogExportDefaults } from './defaults'; 15 | 16 | /** 17 | * Format and sends span information to Datadog Exporter. 18 | */ 19 | export class DatadogExporter implements SpanExporter { 20 | private readonly _logger: api.Logger; 21 | private readonly _exporter: typeof AgentExporter; 22 | private _serviceName: string; 23 | private _env: string | undefined; 24 | private _version: string | undefined; 25 | private _tags: string | undefined; 26 | private _url: string; 27 | private _flushInterval: number; 28 | private _isShutdown: boolean; 29 | 30 | constructor(config: DatadogExporterConfig = {}) { 31 | this._url = 32 | config.agentUrl || 33 | process.env.DD_TRACE_AGENT_URL || 34 | DatadogExportDefaults.AGENT_URL; 35 | this._logger = config.logger || new api.NoopLogger(); 36 | this._serviceName = 37 | config.serviceName || 38 | process.env.DD_SERVICE || 39 | DatadogExportDefaults.SERVICE_NAME; 40 | this._env = config.env || process.env.DD_ENV; 41 | 42 | this._version = config.version || process.env.DD_VERSION; 43 | this._tags = config.tags || process.env.DD_TAGS; 44 | this._flushInterval = 45 | config.flushInterval || DatadogExportDefaults.FLUSH_INTERVAL; 46 | this._exporter = new AgentExporter( 47 | { url: new URL(this._url), flushInterval: this._flushInterval }, 48 | new PrioritySampler() 49 | ); 50 | this._isShutdown = false; 51 | } 52 | 53 | /** 54 | * Called to export sampled {@link ReadableSpan}s. 55 | * @param spans the list of sampled Spans to be exported. 56 | */ 57 | export( 58 | spans: ReadableSpan[], 59 | resultCallback: (result: ExportResult) => void 60 | ): void { 61 | if (this._isShutdown) { 62 | setTimeout(() => 63 | resultCallback({ 64 | code: ExportResultCode.FAILED, 65 | error: new Error('Exporter has been shutdown'), 66 | }) 67 | ); 68 | return; 69 | } 70 | 71 | if (spans.length === 0) { 72 | return resultCallback({ code: ExportResultCode.SUCCESS }); 73 | } 74 | 75 | const formattedDatadogSpans = translateToDatadog( 76 | spans, 77 | this._serviceName, 78 | this._env, 79 | this._version, 80 | this._tags 81 | ); 82 | 83 | try { 84 | this._exporter.export(formattedDatadogSpans); 85 | return resultCallback({ code: ExportResultCode.SUCCESS }); 86 | } catch (error) { 87 | this._logger.debug(error); 88 | return resultCallback({ code: ExportResultCode.FAILED }); 89 | } 90 | } 91 | 92 | /** Stops the exporter. */ 93 | shutdown(): Promise { 94 | this._isShutdown = true; 95 | return new Promise((resolve, reject) => { 96 | if (this._exporter._scheduler !== undefined) { 97 | this._exporter._scheduler.stop(); 98 | } 99 | resolve(); 100 | }); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/datadogProbabilitySampler.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import { Sampler, SamplingDecision, SamplingResult } from '@opentelemetry/api'; 9 | 10 | /** Sampler that samples a given fraction of traces but records all traces. */ 11 | export class DatadogProbabilitySampler implements Sampler { 12 | constructor(private readonly _probability: number = 0) { 13 | this._probability = this._normalize(_probability); 14 | } 15 | 16 | shouldSample(context?: unknown): SamplingResult { 17 | return { 18 | decision: 19 | Math.random() < this._probability 20 | ? SamplingDecision.RECORD_AND_SAMPLED 21 | : SamplingDecision.RECORD, 22 | }; 23 | } 24 | 25 | toString(): string { 26 | // TODO: Consider to use `AlwaysSampleSampler` and `NeverSampleSampler` 27 | // based on the specs. 28 | return `DatadogProbabilitySampler{${this._probability}}`; 29 | } 30 | 31 | private _normalize(probability: number): number { 32 | if (typeof probability !== 'number' || isNaN(probability)) return 0; 33 | return probability >= 1 ? 1 : probability <= 0 ? 0 : probability; 34 | } 35 | } 36 | 37 | export const DATADOG_ALWAYS_SAMPLER = new DatadogProbabilitySampler(1); 38 | export const DATADOG_NEVER_SAMPLER = new DatadogProbabilitySampler(0); 39 | -------------------------------------------------------------------------------- /src/datadogPropagator.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import { 9 | Context, 10 | getSpanContext, 11 | setSpanContext, 12 | isSpanContextValid, 13 | TextMapGetter, 14 | TextMapPropagator, 15 | TextMapSetter, 16 | TraceFlags, 17 | } from '@opentelemetry/api'; 18 | import { TraceState } from '@opentelemetry/core'; 19 | import { id } from './types'; 20 | import { DatadogPropagationDefaults, DatadogDefaults } from './defaults'; 21 | 22 | const VALID_TRACEID_REGEX = /^([0-9a-f]{16}){1,2}$/i; 23 | const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; 24 | const INVALID_ID_REGEX = /^0+$/i; 25 | 26 | function isValidTraceId(traceId: string): boolean { 27 | return VALID_TRACEID_REGEX.test(traceId) && !INVALID_ID_REGEX.test(traceId); 28 | } 29 | 30 | function isValidSpanId(spanId: string): boolean { 31 | return VALID_SPANID_REGEX.test(spanId) && !INVALID_ID_REGEX.test(spanId); 32 | } 33 | 34 | /** 35 | * Propagator for the Datadog HTTP header format. 36 | * Based on: https://github.com/DataDog/dd-trace-js/blob/master/packages/dd-trace/src/opentracing/propagation/text_map.js 37 | */ 38 | export class DatadogPropagator implements TextMapPropagator { 39 | inject(context: Context, carrier: unknown, setter: TextMapSetter): void { 40 | const spanContext = getSpanContext(context); 41 | 42 | if (!spanContext || !isSpanContextValid(spanContext)) return; 43 | 44 | if ( 45 | isValidTraceId(spanContext.traceId) && 46 | isValidSpanId(spanContext.spanId) 47 | ) { 48 | const ddTraceId = id(spanContext.traceId).toString(10); 49 | const ddSpanId = id(spanContext.spanId).toString(10); 50 | 51 | setter.set(carrier, DatadogPropagationDefaults.X_DD_TRACE_ID, ddTraceId); 52 | setter.set(carrier, DatadogPropagationDefaults.X_DD_PARENT_ID, ddSpanId); 53 | 54 | // Current Otel-DD exporter behavior in other languages is to set to zero if falsey 55 | setter.set( 56 | carrier, 57 | DatadogPropagationDefaults.X_DD_SAMPLING_PRIORITY, 58 | (TraceFlags.SAMPLED & spanContext.traceFlags) === TraceFlags.SAMPLED 59 | ? '1' 60 | : '0' 61 | ); 62 | 63 | // Current Otel-DD exporter behavior in other languages is to only set origin tag 64 | // if it exists, otherwise don't set header 65 | if ( 66 | spanContext.traceState !== undefined && 67 | spanContext.traceState.get(DatadogDefaults.OT_ALLOWED_DD_ORIGIN) 68 | ) { 69 | const originString: string = 70 | spanContext.traceState.get(DatadogDefaults.OT_ALLOWED_DD_ORIGIN) || 71 | ''; 72 | 73 | setter.set( 74 | carrier, 75 | DatadogPropagationDefaults.X_DD_ORIGIN, 76 | originString 77 | ); 78 | } 79 | } 80 | } 81 | 82 | extract(context: Context, carrier: unknown, getter: TextMapGetter): Context { 83 | const traceIdHeader = getter.get( 84 | carrier, 85 | DatadogPropagationDefaults.X_DD_TRACE_ID 86 | ); 87 | const spanIdHeader = getter.get( 88 | carrier, 89 | DatadogPropagationDefaults.X_DD_PARENT_ID 90 | ); 91 | const sampledHeader = getter.get( 92 | carrier, 93 | DatadogPropagationDefaults.X_DD_SAMPLING_PRIORITY 94 | ); 95 | const originHeader = getter.get( 96 | carrier, 97 | DatadogPropagationDefaults.X_DD_ORIGIN 98 | ); 99 | 100 | // I suppose header formats can format these as arrays 101 | // keeping this from b3propagator 102 | const traceIdHeaderValue = Array.isArray(traceIdHeader) 103 | ? traceIdHeader[0] 104 | : traceIdHeader; 105 | const spanIdHeaderValue = Array.isArray(spanIdHeader) 106 | ? spanIdHeader[0] 107 | : spanIdHeader; 108 | 109 | const sampled = Array.isArray(sampledHeader) 110 | ? sampledHeader[0] 111 | : sampledHeader; 112 | 113 | const origin = Array.isArray(originHeader) ? originHeader[0] : originHeader; 114 | 115 | // check if we've extracted a trace and span 116 | if (!traceIdHeaderValue || !spanIdHeaderValue) { 117 | return context; 118 | } 119 | 120 | // TODO: is this accurate? 121 | const traceId = id(traceIdHeaderValue, 10).toString('hex'); 122 | const spanId = id(spanIdHeaderValue, 10).toString('hex'); 123 | 124 | if (isValidTraceId(traceId) && isValidSpanId(spanId)) { 125 | const contextOptions: any = { 126 | traceId: traceId, 127 | spanId: spanId, 128 | isRemote: true, 129 | traceFlags: isNaN(Number(sampled)) ? TraceFlags.NONE : Number(sampled), 130 | }; 131 | 132 | if (origin) { 133 | contextOptions[DatadogDefaults.TRACE_STATE] = new TraceState( 134 | `${DatadogDefaults.OT_ALLOWED_DD_ORIGIN}=${origin}` 135 | ); 136 | } 137 | return setSpanContext(context, contextOptions); 138 | } 139 | return context; 140 | } 141 | 142 | fields(): string[] { 143 | return []; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/datadogSpanProcessor.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import { globalErrorHandler, unrefTimer } from '@opentelemetry/core'; 9 | import { 10 | SpanProcessor, 11 | SpanExporter, 12 | ReadableSpan, 13 | } from '@opentelemetry/tracing'; 14 | import { 15 | context, 16 | Logger, 17 | suppressInstrumentation, 18 | NoopLogger, 19 | } from '@opentelemetry/api'; 20 | import { id, DatadogBufferConfig } from './types'; 21 | 22 | // const DEFAULT_BUFFER_SIZE = 100; 23 | const DEFAULT_BUFFER_TIMEOUT_MS = 3_000; 24 | const DEFAULT_MAX_QUEUE_SIZE = 2048; 25 | const DEFAULT_MAX_TRACE_SIZE = 1024; 26 | 27 | /** 28 | * An implementation of the {@link SpanProcessor} that converts the {@link Span} 29 | * to {@link ReadableSpan} and passes it to the configured exporter. 30 | * 31 | * Only spans that are sampled are converted. 32 | */ 33 | export class DatadogSpanProcessor implements SpanProcessor { 34 | private readonly _bufferTimeout: number; 35 | private readonly _maxQueueSize: number; 36 | private readonly _maxTraceSize: number; 37 | private _isShutdown = false; 38 | private _shuttingDownPromise: Promise = Promise.resolve(); 39 | // private _exporter: SpanExporter; 40 | private _timer: NodeJS.Timeout | undefined; 41 | private _traces = new Map(); 42 | private _tracesSpansStarted = new Map(); 43 | private _tracesSpansFinished = new Map(); 44 | private _checkTracesQueue: Set = new Set(); 45 | public readonly logger: Logger; 46 | 47 | constructor( 48 | private readonly _exporter: SpanExporter, 49 | config?: DatadogBufferConfig 50 | ) { 51 | this.logger = (config && config.logger) || new NoopLogger(); 52 | this._bufferTimeout = 53 | config && typeof config.bufferTimeout === 'number' 54 | ? config.bufferTimeout 55 | : DEFAULT_BUFFER_TIMEOUT_MS; 56 | 57 | this._maxQueueSize = 58 | config && typeof config.maxQueueSize === 'number' 59 | ? config.maxQueueSize 60 | : DEFAULT_MAX_QUEUE_SIZE; 61 | this._maxTraceSize = 62 | config && typeof config.maxTraceSize === 'number' 63 | ? config.maxTraceSize 64 | : DEFAULT_MAX_TRACE_SIZE; 65 | } 66 | 67 | forceFlush(): Promise { 68 | if (this._isShutdown) { 69 | return this._shuttingDownPromise; 70 | } 71 | return this._flush(); 72 | } 73 | 74 | shutdown(): Promise { 75 | if (this._isShutdown) { 76 | return this._shuttingDownPromise; 77 | } 78 | this._isShutdown = true; 79 | 80 | this._shuttingDownPromise = new Promise((resolve, reject) => { 81 | Promise.resolve() 82 | .then(() => { 83 | return this._flush(); 84 | }) 85 | .then(() => { 86 | return this._exporter.shutdown(); 87 | }) 88 | .then(resolve) 89 | .catch(e => { 90 | reject(e); 91 | }); 92 | }); 93 | 94 | return this._shuttingDownPromise; 95 | } 96 | 97 | // adds span to queue. 98 | onStart(span: ReadableSpan): void { 99 | if (this._isShutdown) { 100 | return; 101 | } 102 | 103 | if (this._allSpansCount(this._tracesSpansStarted) >= this._maxQueueSize) { 104 | // instead of just dropping all new spans, dd-trace-rb drops a random trace 105 | // https://github.com/DataDog/dd-trace-rb/blob/c6fbf2410a60495f1b2d8912bf7ea7dc63422141/lib/ddtrace/buffer.rb#L34-L36 106 | // It allows for a more fair usage of the queue when under stress load, 107 | // and will create proportional representation of code paths being instrumented at stress time. 108 | const traceToDrop = this._fetchUnfinishedTrace( 109 | this._traces, 110 | this._checkTracesQueue 111 | ); 112 | 113 | if (traceToDrop === undefined) { 114 | this.logger.debug('Max Queue Size reached, dropping span'); 115 | return; 116 | } 117 | this.logger.debug( 118 | `Max Queue Size reached, dropping trace ${traceToDrop}` 119 | ); 120 | this._traces.delete(traceToDrop); 121 | if (this._tracesSpansStarted.has(traceToDrop)) 122 | this._tracesSpansStarted.delete(traceToDrop); 123 | if (this._tracesSpansFinished.has(traceToDrop)) 124 | this._tracesSpansFinished.delete(traceToDrop); 125 | } 126 | 127 | const traceId = span.spanContext.traceId; 128 | 129 | if (!this._traces.has(traceId)) { 130 | this._traces.set(traceId, []); 131 | // this._traces.get(traceId).set(SPANS_KEY, []) 132 | this._tracesSpansStarted.set(traceId, 0); 133 | this._tracesSpansFinished.set(traceId, 0); 134 | } 135 | 136 | const trace = this._traces.get(traceId); 137 | const traceSpansStarted = this._tracesSpansStarted.get(traceId); 138 | 139 | if (traceSpansStarted >= this._maxTraceSize) { 140 | this.logger.debug('Max Trace Size reached, dropping span'); 141 | return; 142 | } 143 | 144 | trace.push(span); 145 | this._tracesSpansStarted.set(traceId, traceSpansStarted + 1); 146 | } 147 | 148 | onEnd(span: ReadableSpan): void { 149 | if (this._isShutdown) { 150 | return; 151 | } 152 | 153 | const traceId = span.spanContext.traceId; 154 | 155 | if (!this._traces.has(traceId)) { 156 | return; 157 | } 158 | 159 | const traceSpansFinished = this._tracesSpansFinished.get(traceId); 160 | 161 | this._tracesSpansFinished.set(traceId, traceSpansFinished + 1); 162 | 163 | if (this._isExportable(traceId)) { 164 | this._checkTracesQueue.add(traceId); 165 | this._maybeStartTimer(); 166 | } 167 | } 168 | 169 | getTraceContext(span: ReadableSpan): (string | undefined)[] { 170 | return [ 171 | id(span.spanContext.traceId), 172 | id(span.spanContext.spanId), 173 | span.parentSpanId ? id(span.parentSpanId) : undefined, 174 | ]; 175 | } 176 | 177 | /** Send the span data list to exporter */ 178 | private _flush(): Promise { 179 | this._clearTimer(); 180 | if (this._checkTracesQueue.size === 0) return Promise.resolve(); 181 | 182 | return new Promise((resolve, reject) => { 183 | // prevent downstream exporter calls from generating spans 184 | context.with(suppressInstrumentation(context.active()), () => { 185 | this._checkTracesQueue.forEach(traceId => { 186 | // check again in case spans have been added 187 | if (this._isExportable(traceId)) { 188 | const spans = this._traces.get(traceId); 189 | this._traces.delete(traceId); 190 | this._tracesSpansStarted.delete(traceId); 191 | this._tracesSpansFinished.delete(traceId); 192 | this._checkTracesQueue.delete(traceId); 193 | this._exporter.export(spans, () => {}); 194 | } else { 195 | this.logger.error(`Trace ${traceId} incomplete, not exported`); 196 | } 197 | }); 198 | 199 | resolve(); 200 | }); 201 | }); 202 | } 203 | 204 | private _maybeStartTimer() { 205 | if (this._timer !== undefined) return; 206 | 207 | this._timer = setTimeout(() => { 208 | this._flush().catch(e => { 209 | globalErrorHandler(e); 210 | }); 211 | }, this._bufferTimeout); 212 | unrefTimer(this._timer); 213 | } 214 | 215 | private _clearTimer() { 216 | if (this._timer !== undefined) { 217 | clearTimeout(this._timer); 218 | this._timer = undefined; 219 | } 220 | } 221 | 222 | private _allSpansCount(traces: Map): number { 223 | // sum all started spans in all traces 224 | return [...traces.values()].reduce((a, b) => a + b, 0); 225 | } 226 | 227 | private _isExportable(traceId: string) { 228 | const trace = this._traces.get(traceId); 229 | 230 | if ( 231 | !trace || 232 | !this._tracesSpansStarted.has(traceId) || 233 | !this._tracesSpansFinished.has(traceId) 234 | ) { 235 | return; 236 | } 237 | 238 | return ( 239 | this._tracesSpansStarted.get(traceId) - 240 | this._tracesSpansFinished.get(traceId) <= 241 | 0 242 | ); 243 | } 244 | 245 | private _fetchUnfinishedTrace( 246 | traces: Map>, 247 | finshedTraceQueue: Set 248 | ): string | undefined { 249 | // don't fetch potentially finished trace awaiting export 250 | const unfinishedTraces = Array.from(traces.keys()).filter( 251 | x => !finshedTraceQueue.has(x) 252 | ); 253 | // grab random unfinished trace id 254 | return unfinishedTraces[ 255 | Math.floor(Math.random() * unfinishedTraces.length) 256 | ]; 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/defaults.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | export enum DatadogDefaults { 9 | /** The datadog formatted origin tag */ 10 | DD_ORIGIN = '_dd_origin', 11 | 12 | /** The otel compliant formatted origin tag */ 13 | OT_ALLOWED_DD_ORIGIN = 'dd_origin', 14 | 15 | /** The otel tracestate key */ 16 | TRACE_STATE = 'traceState', 17 | 18 | /** The datadog formatted sample rate key */ 19 | SAMPLE_RATE_METRIC_KEY = '_sample_rate', 20 | 21 | /** The otel attribute for error type */ 22 | ERR_NAME_SUBSTRING = '.error_name', 23 | 24 | /** The datadog env tag */ 25 | ENV_KEY = 'env', 26 | 27 | /** The datadog version tag */ 28 | VERSION_KEY = 'version', 29 | 30 | /** The datadog error tag name */ 31 | ERROR_TAG = 'error', 32 | 33 | /** A datadog error tag's value */ 34 | ERROR = 1, 35 | 36 | /** The datadog error type tag name */ 37 | ERROR_TYPE_TAG = 'error.type', 38 | 39 | /** A datadog error type's default value */ 40 | ERROR_TYPE_DEFAULT_VALUE = 'ERROR', 41 | 42 | /** The datadog error message tag name */ 43 | ERROR_MSG_TAG = 'error.msg', 44 | 45 | /** The datadog span kind tag name */ 46 | SPAN_KIND = 'span.kind', 47 | 48 | /** The datadog span type tag name */ 49 | SPAN_TYPE = 'span.type', 50 | 51 | /** The datadog resource tag name */ 52 | RESOURCE_TAG = 'resource.name', 53 | 54 | /** The datadog service tag name */ 55 | SERVICE_TAG = 'service.name', 56 | 57 | /** The datadog span kind client name */ 58 | CLIENT = 'client', 59 | 60 | /** The datadog span kind server name */ 61 | SERVER = 'server', 62 | 63 | /** The datadog span kind consumer name */ 64 | PRODUCER = 'worker', 65 | 66 | /** The datadog span kind consumer name */ 67 | CONSUMER = 'worker', 68 | 69 | /** The datadog span kind internal name */ 70 | INTERNAL = 'internal', 71 | 72 | /** The otel traceId name */ 73 | TRACE_ID = 'traceId', 74 | 75 | /** The otel spanId name */ 76 | SPAN_ID = 'spanId', 77 | 78 | /** The otel http method attribute name */ 79 | HTTP_METHOD = 'http.method', 80 | 81 | /** The otel http target attribute name */ 82 | HTTP_TARGET = 'http.target', 83 | } 84 | 85 | export enum DatadogSamplingCodes { 86 | /** The datadog force drop value */ 87 | USER_REJECT = -1, 88 | 89 | /** The datadog auto drop value */ 90 | AUTO_REJECT = 0, 91 | 92 | /** The datadog auto keep value */ 93 | AUTO_KEEP = 1, 94 | } 95 | 96 | export enum DatadogExportDefaults { 97 | /** The default service name. */ 98 | SERVICE_NAME = 'dd-service', 99 | 100 | /** The default datadog agent url. */ 101 | AGENT_URL = 'http://localhost:8126', 102 | 103 | /** 104 | * The default flush interval for the 105 | * Datadog exporter 106 | */ 107 | FLUSH_INTERVAL = 1000, 108 | } 109 | 110 | export enum DatadogPropagationDefaults { 111 | /** The default datadog trace id header*/ 112 | X_DD_TRACE_ID = 'x-datadog-trace-id', 113 | 114 | /** The default datadog parent span id header*/ 115 | X_DD_PARENT_ID = 'x-datadog-parent-id', 116 | 117 | /** The default datadog sampling priority header*/ 118 | X_DD_SAMPLING_PRIORITY = 'x-datadog-sampling-priority', 119 | 120 | /** The default datadog origin header*/ 121 | X_DD_ORIGIN = 'x-datadog-origin', 122 | } 123 | 124 | // otel automatic instrumentation library names 125 | export enum DatadogOtelInstrumentations { 126 | GRPC = '@opentelemetry/plugin-grpc', 127 | HTTP = '@opentelemetry/plugin-http', 128 | HTTPS = '@opentelemetry/plugin-https', 129 | EXPRESS = '@opentelemetry/plugin-express', 130 | IOREDIS = '@opentelemetry/plugin-ioredis', 131 | MONGODB = '@opentelemetry/plugin-mongodb', 132 | MYSQL = '@opentelemetry/plugin-mysql', 133 | PGPOOL = '@opentelemetry/plugin-pg-pool', 134 | PG = '@opentelemetry/plugin-pg', 135 | REDIS = '@opentelemetry/plugin-redis', 136 | } 137 | 138 | // datadog instrumentation library types 139 | export enum DatadogInstrumentationTypes { 140 | WEB = 'web', 141 | HTTP = 'http', 142 | MONGODB = 'mongodb', 143 | REDIS = 'redis', 144 | SQL = 'sql', 145 | } 146 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | export * from './datadog'; 9 | export * from './datadogSpanProcessor'; 10 | export * from './datadogPropagator'; 11 | export * from './datadogProbabilitySampler'; 12 | -------------------------------------------------------------------------------- /src/transform.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import { SpanKind, TraceFlags, StatusCode } from '@opentelemetry/api'; 9 | import { ReadableSpan } from '@opentelemetry/tracing'; 10 | import { hrTimeToMilliseconds } from '@opentelemetry/core'; 11 | import { id, format, Span, Sampler, NoopTracer } from './types'; 12 | import { 13 | DatadogDefaults, 14 | DatadogInstrumentationTypes, 15 | DatadogOtelInstrumentations, 16 | DatadogSamplingCodes, 17 | } from './defaults'; 18 | 19 | const INTERNAL_TRACE_REGEX = /v\d\.\d\/traces/; 20 | 21 | const DD_SPAN_KIND_MAPPING: { [key: string]: DatadogDefaults } = { 22 | [SpanKind.CLIENT]: DatadogDefaults.CLIENT, 23 | [SpanKind.SERVER]: DatadogDefaults.SERVER, 24 | [SpanKind.CONSUMER]: DatadogDefaults.CONSUMER, 25 | [SpanKind.PRODUCER]: DatadogDefaults.PRODUCER, 26 | // When absent, the span is local. 27 | [SpanKind.INTERNAL]: DatadogDefaults.INTERNAL, 28 | }; 29 | 30 | const DD_SPAN_TYPE_MAPPING: { [key: string]: DatadogInstrumentationTypes } = { 31 | [DatadogOtelInstrumentations.GRPC]: DatadogInstrumentationTypes.WEB, 32 | [DatadogOtelInstrumentations.HTTP]: DatadogInstrumentationTypes.HTTP, 33 | [DatadogOtelInstrumentations.HTTPS]: DatadogInstrumentationTypes.HTTP, 34 | [DatadogOtelInstrumentations.EXPRESS]: DatadogInstrumentationTypes.WEB, 35 | [DatadogOtelInstrumentations.IOREDIS]: DatadogInstrumentationTypes.REDIS, 36 | [DatadogOtelInstrumentations.MONGODB]: DatadogInstrumentationTypes.MONGODB, 37 | [DatadogOtelInstrumentations.MYSQL]: DatadogInstrumentationTypes.SQL, 38 | [DatadogOtelInstrumentations.PGPOOL]: DatadogInstrumentationTypes.SQL, 39 | [DatadogOtelInstrumentations.PG]: DatadogInstrumentationTypes.SQL, 40 | [DatadogOtelInstrumentations.REDIS]: DatadogInstrumentationTypes.REDIS, 41 | }; 42 | 43 | // dummy tracer and default sampling logic 44 | const NOOP_TRACER = new NoopTracer(); 45 | const SAMPLER = new Sampler(1); 46 | 47 | /** 48 | * Translate OpenTelemetry ReadableSpans to Datadog Spans 49 | * @param spans Spans to be translated 50 | */ 51 | export function translateToDatadog( 52 | spans: ReadableSpan[], 53 | serviceName: string, 54 | env?: string, 55 | version?: string, 56 | tags?: string 57 | ): typeof Span[] { 58 | return spans 59 | .map(span => { 60 | const defaultTags = createDefaultTags(tags); 61 | const ddSpan = createSpan(span, serviceName, defaultTags, env, version); 62 | return ddSpan; 63 | }) 64 | .map(format); 65 | } 66 | 67 | function createSpan( 68 | span: ReadableSpan, 69 | serviceName: string, 70 | tags: unknown, 71 | env?: string, 72 | version?: string 73 | ): typeof Span { 74 | // convert to datadog span 75 | const [ddTraceId, ddSpanId, ddParentId] = getTraceContext(span); 76 | const [ddResourceTags, ddResourceServiceName] = getResourceInfo(span); 77 | 78 | // generate datadog span base 79 | const ddSpanBase = new Span(NOOP_TRACER, null, SAMPLER, null, { 80 | startTime: hrTimeToMilliseconds(span.startTime), 81 | tags: Object.assign(tags, ddResourceTags), 82 | operationName: createSpanName(span), 83 | }); 84 | const ddSpanBaseContext = ddSpanBase.context(); 85 | ddSpanBaseContext._traceId = ddTraceId; 86 | ddSpanBaseContext._spanId = ddSpanId; 87 | ddSpanBaseContext._parentId = ddParentId; 88 | 89 | // set error code 90 | addErrors(ddSpanBase, span); 91 | 92 | // set span kind 93 | addSpanKind(ddSpanBase, span); 94 | 95 | // set span type 96 | addSpanType(ddSpanBase, span); 97 | 98 | // set datadog specific env and version tags 99 | addDatadogTags( 100 | ddSpanBase, 101 | span, 102 | serviceName, 103 | env, 104 | version, 105 | ddResourceServiceName 106 | ); 107 | 108 | // set sampling rate 109 | setSamplingRate(ddSpanBase, span); 110 | 111 | // set span duration 112 | setDuration(ddSpanBase, span); 113 | 114 | // mark as finished span so that it is exported 115 | ddSpanBaseContext._isFinished = true; 116 | 117 | return ddSpanBase; 118 | } 119 | 120 | function addErrors(ddSpanBase: typeof Span, span: ReadableSpan): void { 121 | // TODO: set error.msg error.type error.stack based on error events 122 | // Determine if OpenTelemetry-JS has implemented https://github.com/open-telemetry/opentelemetry-specification/pull/697 123 | // and if the type and stacktrace are officially recorded. Until this is done, 124 | // we can infer a type by using the status code and also the non spec `.error_name` attribute 125 | if (span.status.code === StatusCode.ERROR) { 126 | ddSpanBase.setTag(DatadogDefaults.ERROR_TAG, DatadogDefaults.ERROR); 127 | ddSpanBase.setTag(DatadogDefaults.ERROR_MSG_TAG, span.status.message); 128 | ddSpanBase.setTag( 129 | DatadogDefaults.ERROR_TYPE_TAG, 130 | DatadogDefaults.ERROR_TYPE_DEFAULT_VALUE 131 | ); 132 | 133 | for (const [key, value] of Object.entries(span.attributes)) { 134 | if (key.indexOf(DatadogDefaults.ERR_NAME_SUBSTRING) >= 0 && value) { 135 | ddSpanBase.setTag(DatadogDefaults.ERROR_TYPE_TAG, value.toString()); 136 | break; 137 | } 138 | } 139 | } 140 | } 141 | 142 | function addSpanKind(ddSpanBase: typeof Span, span: ReadableSpan): void { 143 | if (DD_SPAN_KIND_MAPPING[span.kind]) { 144 | ddSpanBase.setTag( 145 | DatadogDefaults.SPAN_KIND, 146 | DD_SPAN_KIND_MAPPING[span.kind] 147 | ); 148 | } 149 | } 150 | 151 | function addSpanType(ddSpanBase: typeof Span, span: ReadableSpan): void { 152 | // span.instrumentationLibrary.name is not in v0.9.0 but has been merged 153 | if (getInstrumentationName(span)) { 154 | if (DD_SPAN_TYPE_MAPPING[getInstrumentationName(span) || '']) { 155 | ddSpanBase.setTag( 156 | DatadogDefaults.SPAN_TYPE, 157 | DD_SPAN_TYPE_MAPPING[getInstrumentationName(span) || ''] 158 | ); 159 | } 160 | } 161 | } 162 | 163 | function addDatadogTags( 164 | ddSpanBase: typeof Span, 165 | span: ReadableSpan, 166 | serviceName?: string | undefined, 167 | env?: string | undefined, 168 | version?: string | undefined, 169 | ddResourceServiceName?: string | undefined 170 | ): void { 171 | // set reserved service and resource tags 172 | ddSpanBase.addTags({ 173 | [DatadogDefaults.RESOURCE_TAG]: createResource(span), 174 | [DatadogDefaults.SERVICE_TAG]: ddResourceServiceName || serviceName, 175 | }); 176 | 177 | // set env tag 178 | if (env) { 179 | ddSpanBase.setTag(DatadogDefaults.ENV_KEY, env); 180 | } 181 | 182 | // set origin and version on root span only 183 | if (span.parentSpanId === undefined) { 184 | const origin = createOriginString(span); 185 | if (origin) { 186 | ddSpanBase.setTag(DatadogDefaults.DD_ORIGIN, origin); 187 | } 188 | if (version) { 189 | ddSpanBase.setTag(DatadogDefaults.VERSION_KEY, version); 190 | } 191 | } 192 | 193 | // set span attibutes as tags - takes precedence over env vars 194 | // span tags should be strings 195 | for (const [key, value] of Object.entries(span.attributes)) { 196 | if (value !== undefined) { 197 | ddSpanBase.setTag(key, value); 198 | } 199 | } 200 | } 201 | 202 | function getTraceContext(span: ReadableSpan): typeof Span[] { 203 | return [ 204 | id(span.spanContext.traceId), 205 | id(span.spanContext.spanId), 206 | span.parentSpanId ? id(span.parentSpanId) : null, 207 | ]; 208 | } 209 | 210 | function createDefaultTags(tags: string | undefined): unknown { 211 | // Parse a string of tags typically provided via environment variables. 212 | // The expected string is of the form: "key1:value1,key2:value2" 213 | const tagMap: { [key: string]: string } = {}; 214 | const tagArray = tags?.split(',') || []; 215 | for (let i = 0, j = tagArray.length; i < j; i++) { 216 | const kvTuple = tagArray[i].split(':'); 217 | // ensure default tag env var or arg is not malformed 218 | if ( 219 | kvTuple.length !== 2 || 220 | !kvTuple[0] || 221 | !kvTuple[1] || 222 | kvTuple[1].endsWith(':') 223 | ) 224 | return {}; 225 | 226 | tagMap[kvTuple[0]] = kvTuple[1]; 227 | } 228 | return tagMap; 229 | } 230 | 231 | function createOriginString(span: ReadableSpan): string | undefined { 232 | // for some reason traceState keys must be w3c compliant and not stat with underscore 233 | // using dd_origin for internal tracestate and setting datadog tag as _dd_origin 234 | return ( 235 | span.spanContext.traceState && 236 | span.spanContext.traceState.get(DatadogDefaults.OT_ALLOWED_DD_ORIGIN) 237 | ); 238 | } 239 | 240 | function createSpanName(span: ReadableSpan): string | DatadogDefaults { 241 | // span.instrumentationLibrary.name is not in v0.9.0 but has been merged 242 | const instrumentationName = getInstrumentationName(span); 243 | const spanKind = DD_SPAN_KIND_MAPPING[span.kind]; 244 | 245 | if (instrumentationName) { 246 | const sanitizedName = instrumentationName 247 | .replace('@', '') 248 | .replace('/', '_'); 249 | return `${sanitizedName}.${spanKind}`; 250 | } 251 | 252 | return spanKind || span.name; 253 | } 254 | 255 | function createResource(span: ReadableSpan): string { 256 | if (span.attributes[DatadogDefaults.HTTP_METHOD]) { 257 | const route = 258 | span.attributes['http.route'] || 259 | span.attributes[DatadogDefaults.HTTP_TARGET]; 260 | 261 | if (route) { 262 | return `${span.attributes[DatadogDefaults.HTTP_METHOD]} ${route}`; 263 | } 264 | return `${span.attributes[DatadogDefaults.HTTP_METHOD]}`; 265 | } 266 | 267 | return span.name; 268 | } 269 | 270 | function getInstrumentationName(span: any): string | undefined { 271 | return span.instrumentationLibrary && span.instrumentationLibrary.name; 272 | } 273 | 274 | function getSamplingRate(span: ReadableSpan): number { 275 | if ( 276 | (TraceFlags.SAMPLED & span.spanContext.traceFlags) === 277 | TraceFlags.SAMPLED 278 | ) { 279 | return DatadogSamplingCodes.AUTO_KEEP; 280 | } else { 281 | return DatadogSamplingCodes.AUTO_REJECT; 282 | } 283 | } 284 | 285 | function isInternalRequest(span: ReadableSpan): boolean | void { 286 | if (typeof span.attributes['http.target'] === 'string') { 287 | return span.attributes['http.target'].match(INTERNAL_TRACE_REGEX) 288 | ? true 289 | : false; 290 | } 291 | } 292 | 293 | function setDuration(ddSpanBase: typeof Span, span: ReadableSpan): void { 294 | // set span duration 295 | const duration = 296 | hrTimeToMilliseconds(span.endTime) - hrTimeToMilliseconds(span.startTime); 297 | ddSpanBase._duration = duration; 298 | } 299 | 300 | function setSamplingRate(ddSpanBase: typeof Span, span: ReadableSpan): void { 301 | // filter for internal requests to trace-agent and set sampling rate 302 | const samplingRate = getSamplingRate(span); 303 | const internalRequest = isInternalRequest(span); 304 | 305 | if (internalRequest) { 306 | // TODO: add more robust way to drop internal requests 307 | ddSpanBase.context()._traceFlags.sampled = false; 308 | ddSpanBase.context()._sampling.priority = DatadogSamplingCodes.USER_REJECT; 309 | ddSpanBase.setTag( 310 | DatadogDefaults.SAMPLE_RATE_METRIC_KEY, 311 | DatadogSamplingCodes.USER_REJECT 312 | ); 313 | } else if (samplingRate !== undefined) { 314 | ddSpanBase.setTag(DatadogDefaults.SAMPLE_RATE_METRIC_KEY, samplingRate); 315 | } 316 | } 317 | 318 | function getResourceInfo(span: ReadableSpan): any[] { 319 | // extract the resource labels/attributes and potential service name to use for spans 320 | const ddResourceTags: { [key: string]: any } = {}; 321 | let resourceServiceName: any; 322 | const resource: any = span.resource; 323 | 324 | if (!resource) return [ddResourceTags, resourceServiceName]; 325 | 326 | const resourceTags: { [key: string]: string | number } | undefined = 327 | resource['labels'] || resource['attributes']; 328 | 329 | if (!resourceTags) return [ddResourceTags, resourceServiceName]; 330 | 331 | // the spec around whether this is labels or attributes varies between versions 332 | for (const [key, value] of Object.entries(resourceTags)) { 333 | if (key === 'service.name') { 334 | resourceServiceName = value.toString(); 335 | } else { 336 | ddResourceTags[key] = value.toString(); 337 | } 338 | } 339 | 340 | return [ddResourceTags, resourceServiceName]; 341 | } 342 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import * as api from '@opentelemetry/api'; 9 | 10 | /** 11 | * Datadog Exporter config 12 | */ 13 | export interface DatadogExporterConfig { 14 | tags?: string; 15 | logger?: api.Logger; 16 | serviceName?: string; 17 | agentUrl?: string; 18 | version?: string; 19 | env?: string; 20 | flushInterval?: number; 21 | // Optional mapping overrides for OpenTelemetry status code and description. 22 | } 23 | 24 | /** Interface configuration for a Datadog buffer. */ 25 | export interface DatadogBufferConfig { 26 | /** Maximum size of a buffer. */ 27 | maxQueueSize?: number; 28 | maxTraceSize?: number; 29 | /** Max time for a buffer can wait before being sent */ 30 | bufferTimeout?: number; 31 | logger?: api.Logger; 32 | } 33 | 34 | /* eslint-disable @typescript-eslint/no-var-requires */ 35 | export const id = require('dd-trace/packages/dd-trace/src/id'); 36 | export const SpanContext = require('dd-trace/packages/dd-trace/src/opentracing/span_context'); 37 | export const AgentExporter = require('dd-trace/packages/dd-trace/src/exporters/agent'); 38 | export const format = require('dd-trace/packages/dd-trace/src/format'); 39 | export const PrioritySampler = require('dd-trace/packages/dd-trace/src/priority_sampler'); 40 | export const Sampler = require('dd-trace/packages/dd-trace/src/sampler'); 41 | export const Span = require('dd-trace/packages/dd-trace/src/opentracing/span'); 42 | export const NoopTracer = require('dd-trace/packages/dd-trace/src/noop/tracer'); 43 | export const datadog = require('dd-trace'); 44 | /* eslint-enable @typescript-eslint/no-var-requires */ 45 | -------------------------------------------------------------------------------- /src/version.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | // this is autogenerated file, see scripts/version-update.js 9 | export const VERSION = '0.2.0'; 10 | -------------------------------------------------------------------------------- /test/datadog.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import * as assert from 'assert'; 9 | import { DatadogExporter } from '../src'; 10 | import { ExportResult, ExportResultCode } from '@opentelemetry/core'; 11 | import { AgentExporter } from '../src/types'; 12 | import { mockReadableSpan } from './mocks'; 13 | import * as nock from 'nock'; 14 | 15 | describe('DatadogExporter', () => { 16 | describe('constructor', () => { 17 | afterEach(() => { 18 | delete process.env.DD_TRACE_AGENT_URL; 19 | delete process.env.DD_SERVICE; 20 | delete process.env.DD_ENV; 21 | delete process.env.DD_VERSION; 22 | }); 23 | 24 | it('should construct an exporter that contains a writerr', () => { 25 | const exporter = new DatadogExporter({ serviceName: 'opentelemetry' }); 26 | assert.ok(typeof exporter.export === 'function'); 27 | assert.ok(typeof exporter.shutdown === 'function'); 28 | const _exporter = exporter['_exporter']; 29 | 30 | assert.ok(_exporter._writer !== undefined); 31 | assert.strictEqual(exporter['_serviceName'], 'opentelemetry'); 32 | // assert.strictEqual(exporter._tags.length, 0); 33 | }); 34 | 35 | it('should construct an exporter with default url, serviceName, and flushInterval', () => { 36 | const exporter = new DatadogExporter({}); 37 | assert.ok(typeof exporter.export === 'function'); 38 | assert.ok(typeof exporter.shutdown === 'function'); 39 | 40 | assert.strictEqual(exporter['_url'], 'http://localhost:8126'); 41 | assert.strictEqual(exporter['_serviceName'], 'dd-service'); 42 | assert.strictEqual(exporter['_flushInterval'], 1000); 43 | }); 44 | 45 | it('should set env version and tags if configured', () => { 46 | const exporter = new DatadogExporter({ 47 | env: 'prod', 48 | version: 'v1.0', 49 | tags: 'testkey:testvalue', 50 | }); 51 | assert.ok(typeof exporter.export === 'function'); 52 | assert.ok(typeof exporter.shutdown === 'function'); 53 | 54 | assert.strictEqual(exporter['_env'], 'prod'); 55 | assert.strictEqual(exporter['_version'], 'v1.0'); 56 | assert.strictEqual(exporter['_tags'], 'testkey:testvalue'); 57 | }); 58 | 59 | it('should construct an exporter with a flush interval', () => { 60 | const exporter = new DatadogExporter({ 61 | serviceName: 'opentelemetry', 62 | flushInterval: 2000, 63 | }); 64 | 65 | assert.ok(typeof exporter.export === 'function'); 66 | assert.ok(typeof exporter.shutdown === 'function'); 67 | 68 | assert.strictEqual( 69 | exporter['_exporter']['_scheduler']['_interval'], 70 | 2000 71 | ); 72 | }); 73 | 74 | it('should construct an exporter without flushInterval', () => { 75 | const exporter = new DatadogExporter({ 76 | serviceName: 'opentelemetry', 77 | }); 78 | 79 | assert.ok(typeof exporter.export === 'function'); 80 | assert.ok(typeof exporter.shutdown === 'function'); 81 | assert.strictEqual( 82 | exporter['_exporter']['_scheduler']['_interval'], 83 | 1000 84 | ); 85 | }); 86 | 87 | describe('with env vars', () => { 88 | beforeEach(() => { 89 | process.env.DD_TRACE_AGENT_URL = 'http://dd-agent:8125'; 90 | process.env.DD_SERVICE = 'second-service'; 91 | process.env.DD_ENV = 'staging'; 92 | process.env.DD_VERSION = 'v2'; 93 | process.env.DD_TAGS = 'alt_key:alt_value'; 94 | }); 95 | 96 | it('should respect relevant env variables', () => { 97 | const exporter = new DatadogExporter({}); 98 | 99 | assert.strictEqual(exporter['_env'], 'staging'); 100 | assert.strictEqual(exporter['_version'], 'v2'); 101 | assert.strictEqual(exporter['_tags'], 'alt_key:alt_value'); 102 | assert.strictEqual(exporter['_url'], 'http://dd-agent:8125'); 103 | assert.strictEqual(exporter['_serviceName'], 'second-service'); 104 | }); 105 | 106 | it('should prioritize host option over env variable', () => { 107 | const exporter = new DatadogExporter({ 108 | env: 'prod', 109 | version: 'v1', 110 | tags: 'main_key:main_value', 111 | serviceName: 'first-service', 112 | agentUrl: 'http://other-dd-agent:8126', 113 | }); 114 | assert.ok(typeof exporter.export === 'function'); 115 | assert.ok(typeof exporter.shutdown === 'function'); 116 | 117 | assert.strictEqual(exporter['_env'], 'prod'); 118 | assert.strictEqual(exporter['_version'], 'v1'); 119 | assert.strictEqual(exporter['_tags'], 'main_key:main_value'); 120 | assert.strictEqual(exporter['_url'], 'http://other-dd-agent:8126'); 121 | assert.strictEqual(exporter['_serviceName'], 'first-service'); 122 | }); 123 | }); 124 | }); 125 | 126 | describe('export', () => { 127 | let exporter: typeof AgentExporter; 128 | 129 | before(() => { 130 | nock.disableNetConnect(); 131 | exporter = new DatadogExporter({ 132 | serviceName: 'opentelemetry', 133 | flushInterval: 100, 134 | }); 135 | }); 136 | 137 | after(() => { 138 | nock.enableNetConnect(); 139 | exporter.shutdown(); 140 | }); 141 | 142 | it('should skip send with empty list', done => { 143 | const scope = nock('http://localhost:8126') 144 | .put('/v0.4/traces') 145 | .reply(200); 146 | 147 | exporter.export([], (result: ExportResult) => { 148 | setTimeout(() => { 149 | assert.strictEqual(result.code, ExportResultCode.SUCCESS); 150 | assert(scope.isDone() === false); 151 | nock.cleanAll(); 152 | done(); 153 | }, 200); 154 | }); 155 | }); 156 | 157 | it('should send spans to Datadog backend and return with Success', done => { 158 | const scope = nock('http://localhost:8126') 159 | .put('/v0.4/traces') 160 | .reply(200); 161 | 162 | const readableSpan = mockReadableSpan; 163 | 164 | exporter.export([readableSpan], (result: ExportResult) => { 165 | setTimeout(() => { 166 | assert.strictEqual(result.code, ExportResultCode.SUCCESS); 167 | assert(scope.isDone()); 168 | done(); 169 | }, 200); 170 | }); 171 | }); 172 | 173 | it('should returrn Success even with a 4xx response', done => { 174 | const scope = nock('http://localhost:8126') 175 | .put('/v0.4/traces') 176 | .reply(400); 177 | 178 | const readableSpan = mockReadableSpan; 179 | 180 | exporter.export([readableSpan], (result: ExportResult) => { 181 | setTimeout(() => { 182 | assert.strictEqual(result.code, ExportResultCode.SUCCESS); 183 | assert(scope.isDone()); 184 | done(); 185 | }, 200); 186 | }); 187 | }); 188 | }); 189 | }); 190 | -------------------------------------------------------------------------------- /test/datadogProbabilitySampler.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import * as assert from 'assert'; 9 | import * as api from '@opentelemetry/api'; 10 | import { 11 | DatadogProbabilitySampler, 12 | DATADOG_ALWAYS_SAMPLER, 13 | DATADOG_NEVER_SAMPLER, 14 | } from '../src'; 15 | 16 | describe('DatadogProbabilitySampler', () => { 17 | it('should return a DATADOG_ALWAYS_SAMPLER for 1', () => { 18 | const sampler = new DatadogProbabilitySampler(1); 19 | assert.deepStrictEqual(sampler.shouldSample(), { 20 | decision: api.SamplingDecision.RECORD_AND_SAMPLED, 21 | }); 22 | }); 23 | 24 | it('should return a DATADOG_ALWAYS_SAMPLER for >1', () => { 25 | const sampler = new DatadogProbabilitySampler(100); 26 | assert.deepStrictEqual(sampler.shouldSample(), { 27 | decision: api.SamplingDecision.RECORD_AND_SAMPLED, 28 | }); 29 | assert.strictEqual(sampler.toString(), 'DatadogProbabilitySampler{1}'); 30 | }); 31 | 32 | it('should return a DATADOG_NEVER_SAMPLER for 0', () => { 33 | const sampler = new DatadogProbabilitySampler(0); 34 | assert.deepStrictEqual(sampler.shouldSample(), { 35 | decision: api.SamplingDecision.RECORD, 36 | }); 37 | }); 38 | 39 | it('should return a DATADOG_NEVER_SAMPLER for <0', () => { 40 | const sampler = new DatadogProbabilitySampler(-1); 41 | assert.deepStrictEqual(sampler.shouldSample(), { 42 | decision: api.SamplingDecision.RECORD, 43 | }); 44 | }); 45 | 46 | it('should sample according to the probability', () => { 47 | Math.random = () => 1 / 10; 48 | const sampler = new DatadogProbabilitySampler(0.2); 49 | assert.deepStrictEqual(sampler.shouldSample(), { 50 | decision: api.SamplingDecision.RECORD_AND_SAMPLED, 51 | }); 52 | assert.strictEqual(sampler.toString(), 'DatadogProbabilitySampler{0.2}'); 53 | 54 | Math.random = () => 5 / 10; 55 | assert.deepStrictEqual(sampler.shouldSample(), { 56 | decision: api.SamplingDecision.RECORD, 57 | }); 58 | }); 59 | 60 | it('should return api.SamplingDecision.RECORD_AND_SAMPLED for DATADOG_ALWAYS_SAMPLER', () => { 61 | assert.deepStrictEqual(DATADOG_ALWAYS_SAMPLER.shouldSample(), { 62 | decision: api.SamplingDecision.RECORD_AND_SAMPLED, 63 | }); 64 | assert.strictEqual( 65 | DATADOG_ALWAYS_SAMPLER.toString(), 66 | 'DatadogProbabilitySampler{1}' 67 | ); 68 | }); 69 | 70 | it('should return decision: api.SamplingDecision.RECORD for DATADOG_NEVER_SAMPLER', () => { 71 | assert.deepStrictEqual(DATADOG_NEVER_SAMPLER.shouldSample(), { 72 | decision: api.SamplingDecision.RECORD, 73 | }); 74 | assert.strictEqual( 75 | DATADOG_NEVER_SAMPLER.toString(), 76 | 'DatadogProbabilitySampler{0}' 77 | ); 78 | }); 79 | 80 | it('should handle NaN', () => { 81 | const sampler = new DatadogProbabilitySampler(NaN); 82 | assert.deepStrictEqual(sampler.shouldSample(), { 83 | decision: api.SamplingDecision.RECORD, 84 | }); 85 | assert.strictEqual(sampler.toString(), 'DatadogProbabilitySampler{0}'); 86 | }); 87 | 88 | it('should handle -NaN', () => { 89 | const sampler = new DatadogProbabilitySampler(-NaN); 90 | assert.deepStrictEqual(sampler.shouldSample(), { 91 | decision: api.SamplingDecision.RECORD, 92 | }); 93 | assert.strictEqual(sampler.toString(), 'DatadogProbabilitySampler{0}'); 94 | }); 95 | 96 | it('should handle undefined', () => { 97 | const sampler = new DatadogProbabilitySampler(undefined); 98 | assert.deepStrictEqual(sampler.shouldSample(), { 99 | decision: api.SamplingDecision.RECORD, 100 | }); 101 | assert.strictEqual(sampler.toString(), 'DatadogProbabilitySampler{0}'); 102 | }); 103 | }); 104 | -------------------------------------------------------------------------------- /test/datadogPropagator.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import { 9 | defaultTextMapGetter, 10 | defaultTextMapSetter, 11 | SpanContext, 12 | TraceFlags, 13 | ROOT_CONTEXT, 14 | setSpanContext, 15 | getSpanContext, 16 | } from '@opentelemetry/api'; 17 | import * as assert from 'assert'; 18 | import { TraceState } from '@opentelemetry/core'; 19 | import { DatadogPropagator } from '../src/'; 20 | import { id } from '../src/types'; 21 | import { DatadogPropagationDefaults } from '../src/defaults'; 22 | 23 | describe('DatadogPropagator', () => { 24 | const datadogPropagator = new DatadogPropagator(); 25 | let carrier: { [key: string]: unknown }; 26 | 27 | beforeEach(() => { 28 | carrier = {}; 29 | }); 30 | 31 | describe('.inject()', () => { 32 | it('should set datadog traceId and spanId headers', () => { 33 | const traceId = 'd4cda95b652f4a1592b449d5929fda1b'; 34 | const spanId = '6e0c63257de34c92'; 35 | const spanContext: SpanContext = { 36 | traceId: traceId, 37 | spanId: spanId, 38 | traceFlags: TraceFlags.SAMPLED, 39 | }; 40 | 41 | datadogPropagator.inject( 42 | setSpanContext(ROOT_CONTEXT, spanContext), 43 | carrier, 44 | defaultTextMapSetter 45 | ); 46 | assert.deepStrictEqual( 47 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID], 48 | id(traceId).toString(10) 49 | ); 50 | assert.deepStrictEqual( 51 | carrier[DatadogPropagationDefaults.X_DD_PARENT_ID], 52 | id(spanId).toString(10) 53 | ); 54 | assert.deepStrictEqual( 55 | carrier[DatadogPropagationDefaults.X_DD_SAMPLING_PRIORITY], 56 | '1' 57 | ); 58 | }); 59 | 60 | it('should set b3 traceId and spanId headers and also traceflags and tracestate', () => { 61 | const traceId = 'd4cda95b652f4a1592b449d5929fda1b'; 62 | const spanId = '6e0c63257de34c92'; 63 | const spanContext: SpanContext = { 64 | traceId: traceId, 65 | spanId: spanId, 66 | traceFlags: TraceFlags.NONE, 67 | traceState: new TraceState('dd_origin=synthetics-example'), 68 | isRemote: true, 69 | }; 70 | 71 | datadogPropagator.inject( 72 | setSpanContext(ROOT_CONTEXT, spanContext), 73 | carrier, 74 | defaultTextMapSetter 75 | ); 76 | assert.deepStrictEqual( 77 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID], 78 | id(traceId).toString(10) 79 | ); 80 | assert.deepStrictEqual( 81 | carrier[DatadogPropagationDefaults.X_DD_PARENT_ID], 82 | id(spanId).toString(10) 83 | ); 84 | assert.deepStrictEqual( 85 | carrier[DatadogPropagationDefaults.X_DD_SAMPLING_PRIORITY], 86 | '0' 87 | ); 88 | assert.deepStrictEqual( 89 | carrier[DatadogPropagationDefaults.X_DD_ORIGIN], 90 | 'synthetics-example' 91 | ); 92 | }); 93 | 94 | it('should not inject empty spancontext', () => { 95 | const emptySpanContext = { 96 | traceId: '', 97 | spanId: '', 98 | traceFlags: TraceFlags.NONE, 99 | }; 100 | datadogPropagator.inject( 101 | setSpanContext(ROOT_CONTEXT, emptySpanContext), 102 | carrier, 103 | defaultTextMapSetter 104 | ); 105 | assert.deepStrictEqual( 106 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID], 107 | undefined 108 | ); 109 | assert.deepStrictEqual( 110 | carrier[DatadogPropagationDefaults.X_DD_PARENT_ID], 111 | undefined 112 | ); 113 | }); 114 | }); 115 | 116 | describe('.extract()', () => { 117 | it('should extract context of a unsampled span from carrier', () => { 118 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID] = id( 119 | '0af7651916cd43dd8448eb211c80319c' 120 | ).toString(10); 121 | carrier[DatadogPropagationDefaults.X_DD_PARENT_ID] = id( 122 | 'b7ad6b7169203331' 123 | ).toString(10); 124 | const extractedSpanContext = getSpanContext( 125 | datadogPropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter) 126 | ); 127 | 128 | assert.deepStrictEqual(extractedSpanContext, { 129 | spanId: 'b7ad6b7169203331', 130 | traceId: '0af7651916cd43dd', 131 | isRemote: true, 132 | traceFlags: TraceFlags.NONE, 133 | }); 134 | }); 135 | 136 | it('should extract context of a sampled span from carrier', () => { 137 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID] = id( 138 | '0af7651916cd43dd8448eb211c80319c' 139 | ).toString(10); 140 | carrier[DatadogPropagationDefaults.X_DD_PARENT_ID] = id( 141 | 'b7ad6b7169203331' 142 | ).toString(10); 143 | carrier[DatadogPropagationDefaults.X_DD_SAMPLING_PRIORITY] = '1'; 144 | 145 | const extractedSpanContext = getSpanContext( 146 | datadogPropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter) 147 | ); 148 | 149 | assert.deepStrictEqual(extractedSpanContext, { 150 | spanId: 'b7ad6b7169203331', 151 | traceId: '0af7651916cd43dd', 152 | isRemote: true, 153 | traceFlags: TraceFlags.SAMPLED, 154 | }); 155 | }); 156 | 157 | it('should return undefined when traceId is undefined', () => { 158 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID] = undefined; 159 | carrier[DatadogPropagationDefaults.X_DD_PARENT_ID] = undefined; 160 | assert.deepStrictEqual( 161 | getSpanContext( 162 | datadogPropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter) 163 | ), 164 | undefined 165 | ); 166 | }); 167 | 168 | it('should return undefined when options and spanId are undefined', () => { 169 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID] = id( 170 | '0af7651916cd43dd8448eb211c80319c' 171 | ).toString(10); 172 | carrier[DatadogPropagationDefaults.X_DD_PARENT_ID] = undefined; 173 | assert.deepStrictEqual( 174 | getSpanContext( 175 | datadogPropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter) 176 | ), 177 | undefined 178 | ); 179 | }); 180 | 181 | it('returns undefined if datadog header is missing', () => { 182 | assert.deepStrictEqual( 183 | getSpanContext( 184 | datadogPropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter) 185 | ), 186 | undefined 187 | ); 188 | }); 189 | 190 | it('returns undefined if datadog header is invalid', () => { 191 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID] = 'invalid!'; 192 | assert.deepStrictEqual( 193 | getSpanContext( 194 | datadogPropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter) 195 | ), 196 | undefined 197 | ); 198 | }); 199 | 200 | it('extracts datadog from list of header', () => { 201 | carrier[DatadogPropagationDefaults.X_DD_TRACE_ID] = [ 202 | id('0af7651916cd43dd8448eb211c80319c').toString(10), 203 | ]; 204 | carrier[DatadogPropagationDefaults.X_DD_PARENT_ID] = id( 205 | 'b7ad6b7169203331' 206 | ).toString(10); 207 | carrier[DatadogPropagationDefaults.X_DD_SAMPLING_PRIORITY] = '01'; 208 | const extractedSpanContext = getSpanContext( 209 | datadogPropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter) 210 | ); 211 | 212 | assert.deepStrictEqual(extractedSpanContext, { 213 | spanId: 'b7ad6b7169203331', 214 | traceId: '0af7651916cd43dd', 215 | isRemote: true, 216 | traceFlags: TraceFlags.SAMPLED, 217 | }); 218 | }); 219 | 220 | it('should fail gracefully on bad responses from getter', () => { 221 | const ctx1 = datadogPropagator.extract(ROOT_CONTEXT, carrier, { 222 | // @ts-expect-error verify number is not allowed 223 | get: (c, k) => 1, // not a number 224 | keys: defaultTextMapGetter.keys, 225 | }); 226 | const ctx2 = datadogPropagator.extract(ROOT_CONTEXT, carrier, { 227 | get: (c, k) => [], // empty array 228 | keys: defaultTextMapGetter.keys, 229 | }); 230 | const ctx3 = datadogPropagator.extract(ROOT_CONTEXT, carrier, { 231 | get: (c, k) => undefined, // missing value 232 | keys: defaultTextMapGetter.keys, 233 | }); 234 | 235 | assert.ok(ctx1 === ROOT_CONTEXT); 236 | assert.ok(ctx2 === ROOT_CONTEXT); 237 | assert.ok(ctx3 === ROOT_CONTEXT); 238 | }); 239 | 240 | // TODO: this is implemented for b3 64 bit, not sure if we should implement for datadog 241 | // it('should left-pad 64 bit trace ids with 0', () => { 242 | // }); 243 | }); 244 | }); 245 | -------------------------------------------------------------------------------- /test/datadogSpanProcessor.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import { TraceFlags, setSpanContext, ROOT_CONTEXT } from '@opentelemetry/api'; 9 | import { 10 | InMemorySpanExporter, 11 | BasicTracerProvider, 12 | Span, 13 | } from '@opentelemetry/tracing'; 14 | import * as assert from 'assert'; 15 | import * as sinon from 'sinon'; 16 | import { DatadogSpanProcessor, DATADOG_ALWAYS_SAMPLER } from '../src'; 17 | 18 | function createSampledSpan(spanName: string, parent?: boolean): Span { 19 | const tracer = new BasicTracerProvider({ 20 | sampler: DATADOG_ALWAYS_SAMPLER, 21 | }).getTracer('default'); 22 | const span = parent 23 | ? tracer.startSpan( 24 | spanName, 25 | {}, 26 | setSpanContext(ROOT_CONTEXT, { 27 | traceId: 'd4cda95b652f4a1592b449d5929fda1b', 28 | spanId: '6e0c63257de34c92', 29 | traceFlags: TraceFlags.SAMPLED, 30 | }) 31 | ) 32 | : tracer.startSpan(spanName); 33 | 34 | span.end(); 35 | 36 | return span as Span; 37 | } 38 | 39 | describe('DatadogSpanProcessor', () => { 40 | const name = 'span-name'; 41 | const defaultProcessorConfig = { 42 | maxQueueSize: 10, 43 | maxTraceSize: 3, 44 | bufferTimeout: 3000, 45 | }; 46 | let exporter: InMemorySpanExporter; 47 | beforeEach(() => { 48 | exporter = new InMemorySpanExporter(); 49 | }); 50 | afterEach(() => { 51 | exporter.reset(); 52 | sinon.restore(); 53 | }); 54 | 55 | describe('constructor', () => { 56 | it('should create a DatadogSpanProcessor instance', () => { 57 | const processor = new DatadogSpanProcessor(exporter); 58 | assert.ok(processor instanceof DatadogSpanProcessor); 59 | processor.shutdown(); 60 | }); 61 | 62 | it('should create a DatadogSpanProcessor instance with config', () => { 63 | const processor = new DatadogSpanProcessor( 64 | exporter, 65 | defaultProcessorConfig 66 | ); 67 | assert.ok(processor instanceof DatadogSpanProcessor); 68 | assert.strictEqual(processor['_maxQueueSize'], 10); 69 | assert.strictEqual(processor['_maxTraceSize'], 3); 70 | processor.shutdown(); 71 | }); 72 | 73 | it('should create a DatadogSpanProcessor instance with empty config', () => { 74 | const processor = new DatadogSpanProcessor(exporter, {}); 75 | assert.ok(processor instanceof DatadogSpanProcessor); 76 | processor.shutdown(); 77 | }); 78 | }); 79 | 80 | describe('.onStart/.onEnd/.shutdown', () => { 81 | it('should do nothing after processor is shutdown', () => { 82 | const processor = new DatadogSpanProcessor( 83 | exporter, 84 | defaultProcessorConfig 85 | ); 86 | const spy: sinon.SinonSpy = sinon.spy(exporter, 'export') as any; 87 | const span = createSampledSpan(`${name}_0`); 88 | 89 | processor.onStart(span); 90 | processor.onEnd(span); 91 | assert.strictEqual(processor['_traces'].size, 1); 92 | 93 | return processor.forceFlush().then(() => { 94 | assert.strictEqual(exporter.getFinishedSpans().length, 1); 95 | 96 | processor.onStart(span); 97 | processor.onEnd(span); 98 | assert.strictEqual(processor['_traces'].size, 1); 99 | 100 | assert.strictEqual(spy.args.length, 1); 101 | return processor.shutdown().then(() => { 102 | assert.strictEqual(spy.args.length, 2); 103 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 104 | 105 | processor.onStart(span); 106 | processor.onEnd(span); 107 | assert.strictEqual(spy.args.length, 2); 108 | assert.strictEqual(processor['_traces'].size, 0); 109 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 110 | }); 111 | }); 112 | }); 113 | 114 | it.skip('should reach but not exceed the max buffer size', () => { 115 | const exporter = new InMemorySpanExporter(); 116 | const processor = new DatadogSpanProcessor( 117 | exporter, 118 | defaultProcessorConfig 119 | ); 120 | const maxQueueSize = defaultProcessorConfig.maxQueueSize; 121 | const aboveMaxQueueSize = maxQueueSize + 1; 122 | for (let i = 0; i < aboveMaxQueueSize; i++) { 123 | const span = createSampledSpan(`${name}_${i}`); 124 | processor.onStart(span); 125 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 126 | 127 | processor.onEnd(span); 128 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 129 | } 130 | 131 | //export all traces 132 | return processor.forceFlush().then(() => { 133 | assert.strictEqual(exporter.getFinishedSpans().length, maxQueueSize); 134 | 135 | return processor.shutdown().then(() => { 136 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 137 | }); 138 | }); 139 | }); 140 | 141 | it('should reach but not exceed the max trace size', () => { 142 | const processor = new DatadogSpanProcessor( 143 | exporter, 144 | defaultProcessorConfig 145 | ); 146 | const maxTraceSize = defaultProcessorConfig.maxTraceSize; 147 | const aboveMaxTraceSize = maxTraceSize + 1; 148 | 149 | for (let i = 0; i < aboveMaxTraceSize; i++) { 150 | const span = createSampledSpan(`${name}_${i}`, true); 151 | processor.onStart(span); 152 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 153 | 154 | processor.onEnd(span); 155 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 156 | } 157 | 158 | //export all traces 159 | return processor.forceFlush().then(() => { 160 | assert.strictEqual(exporter.getFinishedSpans().length, maxTraceSize); 161 | 162 | return processor.shutdown().then(() => { 163 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 164 | }); 165 | }); 166 | }); 167 | 168 | it.skip('should force flush on demand', () => { 169 | const processor = new DatadogSpanProcessor( 170 | exporter, 171 | defaultProcessorConfig 172 | ); 173 | for (let i = 0; i < defaultProcessorConfig.maxQueueSize; i++) { 174 | const span = createSampledSpan(`${name}_${i}`); 175 | processor.onStart(span); 176 | processor.onEnd(span); 177 | } 178 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 179 | return processor.forceFlush().then(() => { 180 | assert.strictEqual( 181 | exporter.getFinishedSpans().length, 182 | defaultProcessorConfig.maxQueueSize 183 | ); 184 | }); 185 | }); 186 | 187 | it('should not export empty span lists', done => { 188 | const spy = sinon.spy(exporter, 'export'); 189 | const clock = sinon.useFakeTimers(); 190 | 191 | const tracer = new BasicTracerProvider({ 192 | sampler: DATADOG_ALWAYS_SAMPLER, 193 | }).getTracer('default'); 194 | const processor = new DatadogSpanProcessor( 195 | exporter, 196 | defaultProcessorConfig 197 | ); 198 | 199 | // start but do not end spans 200 | for (let i = 0; i < defaultProcessorConfig.maxQueueSize; i++) { 201 | const span = tracer.startSpan('spanName'); 202 | processor.onStart(span as Span); 203 | } 204 | 205 | setTimeout(() => { 206 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 207 | // after the timeout, export should not have been called 208 | // because no spans are ended 209 | sinon.assert.notCalled(spy); 210 | done(); 211 | }, defaultProcessorConfig.bufferTimeout + 2000); 212 | 213 | // no spans have been finished 214 | assert.strictEqual(exporter.getFinishedSpans().length, 0); 215 | clock.tick(defaultProcessorConfig.bufferTimeout + 2000); 216 | 217 | clock.restore(); 218 | }); 219 | }); 220 | }); 221 | -------------------------------------------------------------------------------- /test/mocks.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import { SpanKind, StatusCode, TraceFlags } from '@opentelemetry/api'; 9 | // import { ReadableSpan } from '@opentelemetry/tracing'; 10 | import { Resource } from '@opentelemetry/resources'; 11 | import { TraceState } from '@opentelemetry/core'; 12 | 13 | export const mockResourceServiceName = 'otel-resource-service-name'; 14 | 15 | export const mockSpanContextUnsampled = { 16 | traceId: 'd4cda95b652f4a1592b449d5929fda1b', 17 | spanId: '6e0c63257de34c92', 18 | traceFlags: TraceFlags.NONE, 19 | }; 20 | 21 | export const mockSpanContextSampled = { 22 | traceId: 'd4cda95b652f4a1592b449d5929fda1b', 23 | spanId: '6e0c63257de34c92', 24 | traceFlags: TraceFlags.SAMPLED, 25 | }; 26 | 27 | export const mockSpanContextOrigin = { 28 | traceId: 'd4cda95b652f4a1592b449d5929fda1b', 29 | spanId: '6e0c63257de34c92', 30 | traceFlags: TraceFlags.SAMPLED, 31 | traceState: new TraceState('dd_origin=synthetics-example'), 32 | }; 33 | 34 | export const mockReadableSpan: any = { 35 | name: 'my-span1', 36 | kind: SpanKind.CLIENT, 37 | spanContext: mockSpanContextUnsampled, 38 | startTime: [1566156729, 709], 39 | endTime: [1566156731, 709], 40 | ended: true, 41 | status: { 42 | code: StatusCode.ERROR, 43 | }, 44 | attributes: {}, 45 | links: [], 46 | events: [], 47 | duration: [32, 800000000], 48 | resource: Resource.empty(), 49 | instrumentationLibrary: { 50 | name: 'default', 51 | version: '0.0.1', 52 | }, 53 | }; 54 | 55 | export const mockExandedReadableSpan: any = { 56 | name: 'my-span', 57 | kind: SpanKind.INTERNAL, 58 | spanContext: mockSpanContextUnsampled, 59 | startTime: [1566156729, 709], 60 | endTime: [1566156731, 709], 61 | ended: true, 62 | status: { 63 | code: StatusCode.OK, 64 | }, 65 | attributes: { 66 | testBool: true, 67 | testString: 'test', 68 | testNum: '3.142', 69 | }, 70 | links: [ 71 | { 72 | context: { 73 | traceId: 'a4cda95b652f4a1592b449d5929fda1b', 74 | spanId: '3e0c63257de34c92', 75 | }, 76 | attributes: { 77 | testBool: true, 78 | testString: 'test', 79 | testNum: 3.142, 80 | }, 81 | }, 82 | ], 83 | events: [ 84 | { 85 | name: 'something happened', 86 | attributes: { 87 | error: true, 88 | }, 89 | time: [1566156729, 809], 90 | }, 91 | ], 92 | duration: [32, 800000000], 93 | resource: new Resource({ 94 | zervice: 'ui', 95 | otherInfo: 'one', 96 | cost: 112.12, 97 | }), 98 | instrumentationLibrary: { 99 | name: 'default', 100 | version: '0.0.1', 101 | }, 102 | }; 103 | 104 | export const mockExandedReadableSpanWithResourceService: any = { 105 | name: 'my-span', 106 | kind: SpanKind.INTERNAL, 107 | spanContext: mockSpanContextUnsampled, 108 | startTime: [1566156729, 709], 109 | endTime: [1566156731, 709], 110 | ended: true, 111 | status: { 112 | code: StatusCode.OK, 113 | }, 114 | attributes: { 115 | testBool: true, 116 | testString: 'test', 117 | testNum: '3.142', 118 | }, 119 | links: [ 120 | { 121 | context: { 122 | traceId: 'a4cda95b652f4a1592b449d5929fda1b', 123 | spanId: '3e0c63257de34c92', 124 | }, 125 | attributes: { 126 | testBool: true, 127 | testString: 'test', 128 | testNum: 3.142, 129 | }, 130 | }, 131 | ], 132 | events: [ 133 | { 134 | name: 'something happened', 135 | attributes: { 136 | error: true, 137 | }, 138 | time: [1566156729, 809], 139 | }, 140 | ], 141 | duration: [32, 800000000], 142 | resource: new Resource({ 143 | 'service.name': mockResourceServiceName, 144 | otherInfo: 'one', 145 | cost: 112.12, 146 | }), 147 | instrumentationLibrary: { 148 | name: 'default', 149 | version: '0.0.1', 150 | }, 151 | }; 152 | -------------------------------------------------------------------------------- /test/transform.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Unless explicitly stated otherwise all files in this repository are licensed 3 | * under the Apache 2.0 license (see LICENSE). 4 | * This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | * Copyright 2020 Datadog, Inc. 6 | */ 7 | 8 | import * as assert from 'assert'; 9 | import { StatusCode, SpanKind } from '@opentelemetry/api'; 10 | import { ReadableSpan } from '@opentelemetry/tracing'; 11 | import { hrTimeToMilliseconds } from '@opentelemetry/core'; 12 | import { id } from '../src/types'; 13 | import { translateToDatadog } from '../src/transform'; 14 | import { 15 | mockSpanContextUnsampled, 16 | mockSpanContextSampled, 17 | mockSpanContextOrigin, 18 | mockExandedReadableSpan, 19 | mockExandedReadableSpanWithResourceService, 20 | mockResourceServiceName, 21 | } from './mocks'; 22 | 23 | describe('transform', () => { 24 | const spanContextUnsampled = mockSpanContextUnsampled; 25 | 26 | const spanContextSampled = mockSpanContextSampled; 27 | 28 | const spanContextOrigin = mockSpanContextOrigin; 29 | 30 | const parentSpanId = '6e0c63257de34c93'; 31 | const serviceName = 'my-service'; 32 | 33 | const generateOtelSpans = function (options: any): ReadableSpan[] { 34 | const otelSpans = []; 35 | const span: ReadableSpan = mockExandedReadableSpan; 36 | const updatedSpan = Object.assign(span, options); 37 | otelSpans.push(updatedSpan); 38 | return otelSpans; 39 | }; 40 | 41 | const generateOtelSpansWithResourceService = function ( 42 | options: any 43 | ): ReadableSpan[] { 44 | const otelSpans = []; 45 | const span: ReadableSpan = mockExandedReadableSpanWithResourceService; 46 | const updatedSpan = Object.assign(span, options); 47 | otelSpans.push(updatedSpan); 48 | return otelSpans; 49 | }; 50 | 51 | describe('translateToDatadog', () => { 52 | it('should convert an OpenTelemetry span and its properties, including resource info, to a finished DatadogSpan', () => { 53 | const spans = generateOtelSpans({ spanContext: spanContextUnsampled }); 54 | const datadogSpans = translateToDatadog(spans, serviceName); 55 | const datadogSpan = datadogSpans[0]; 56 | 57 | assert.deepStrictEqual(datadogSpan.name, 'default.internal'); 58 | assert.deepStrictEqual(datadogSpan.meta['span.kind'], 'internal'); 59 | assert.deepStrictEqual(datadogSpan.resource, spans[0].name); 60 | assert.deepStrictEqual(datadogSpan.service, serviceName); 61 | 62 | assert.deepStrictEqual( 63 | datadogSpan.trace_id, 64 | id(spanContextUnsampled.traceId) 65 | ); 66 | 67 | assert.deepStrictEqual( 68 | datadogSpan.span_id.toString('hex'), 69 | spanContextUnsampled.spanId 70 | ); 71 | 72 | assert.deepStrictEqual( 73 | datadogSpan.parent_id.toString('hex'), 74 | '0000000000000000' 75 | ); 76 | assert.deepStrictEqual(datadogSpan.error, 0); 77 | assert.deepStrictEqual( 78 | datadogSpan.start, 79 | Math.round(hrTimeToMilliseconds(spans[0].startTime) * 1e6) 80 | ); 81 | 82 | assert.strictEqual(Object.keys(datadogSpan.meta).length, 7); 83 | assert.strictEqual(Object.keys(datadogSpan.metrics).length, 1); 84 | assert.strictEqual( 85 | datadogSpan.metrics['_sample_rate'], 86 | spanContextUnsampled.traceFlags 87 | ); 88 | assert.strictEqual(datadogSpan.duration > 0, true); 89 | }); 90 | 91 | it('should sample spans with sampled traceFlag', () => { 92 | const spans = generateOtelSpans({ spanContext: spanContextSampled }); 93 | const datadogSpans = translateToDatadog(spans, serviceName); 94 | const datadogSpan = datadogSpans[0]; 95 | 96 | assert.strictEqual( 97 | datadogSpan.metrics['_sample_rate'], 98 | spanContextSampled.traceFlags 99 | ); 100 | }); 101 | 102 | it('should set origin tag for spans with origin traceState', () => { 103 | const spans = generateOtelSpans({ spanContext: spanContextOrigin }); 104 | const datadogSpans = translateToDatadog(spans, serviceName); 105 | const datadogSpan = datadogSpans[0]; 106 | 107 | assert.strictEqual(datadogSpan.meta['_dd_origin'], 'synthetics-example'); 108 | }); 109 | 110 | it('should set tags based on the env, origin, and tags arguments', () => { 111 | const spans = generateOtelSpans({ spanContext: spanContextOrigin }); 112 | const datadogSpans = translateToDatadog( 113 | spans, 114 | serviceName, 115 | 'test_env', 116 | 'v1.0', 117 | 'is_test:true' 118 | ); 119 | const datadogSpan = datadogSpans[0]; 120 | 121 | assert.strictEqual(datadogSpan.meta['_dd_origin'], 'synthetics-example'); 122 | assert.strictEqual(datadogSpan.meta['env'], 'test_env'); 123 | assert.strictEqual(datadogSpan.meta['version'], 'v1.0'); 124 | assert.strictEqual(datadogSpan.meta['is_test'], 'true'); 125 | }); 126 | 127 | it('should not set origin or version tag for child spans ', () => { 128 | const spans = generateOtelSpans({ 129 | spanContext: spanContextOrigin, 130 | parentSpanId: parentSpanId, 131 | }); 132 | const datadogSpans = translateToDatadog( 133 | spans, 134 | serviceName, 135 | 'test_env', 136 | 'v1.0', 137 | 'is_test:true' 138 | ); 139 | const datadogSpan = datadogSpans[0]; 140 | 141 | assert.strictEqual(datadogSpan.meta['_dd_origin'], undefined); 142 | assert.strictEqual(datadogSpan.meta['version'], undefined); 143 | }); 144 | 145 | it('should set an error and its tags on the datadog span when the otel span has a not OK status', () => { 146 | const spans = generateOtelSpans({ 147 | spanContext: spanContextSampled, 148 | status: { 149 | code: StatusCode.ERROR, 150 | message: 'error message', 151 | }, 152 | kind: SpanKind.CONSUMER, 153 | }); 154 | const datadogSpans = translateToDatadog(spans, serviceName); 155 | const datadogSpan = datadogSpans[0]; 156 | 157 | assert.strictEqual(datadogSpan.error, 1); 158 | assert.strictEqual(datadogSpan.meta['error.msg'], 'error message'); 159 | assert.strictEqual(datadogSpan.meta['error.type'], 'ERROR'); 160 | }); 161 | 162 | it('should set the sampling rate to -1 for internally generated traces', () => { 163 | const spans = generateOtelSpans({ 164 | spanContext: spanContextSampled, 165 | attributes: { 166 | 'http.target': '/v0.4/traces/', 167 | }, 168 | }); 169 | const datadogSpans = translateToDatadog(spans, serviceName); 170 | const datadogSpan = datadogSpans[0]; 171 | assert.strictEqual(datadogSpan.metrics['_sample_rate'], -1); 172 | }); 173 | 174 | it('should set the resource service.name as dd span service if it exists', () => { 175 | const spans = generateOtelSpansWithResourceService({ 176 | spanContext: spanContextSampled, 177 | }); 178 | const datadogSpans = translateToDatadog(spans, serviceName); 179 | const datadogSpan = datadogSpans[0]; 180 | assert.strictEqual(datadogSpan.service, mockResourceServiceName); 181 | }); 182 | }); 183 | }); 184 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowUnreachableCode": false, 4 | "allowUnusedLabels": false, 5 | "declaration": true, 6 | "declarationMap": true, 7 | "forceConsistentCasingInFileNames": true, 8 | "module": "commonjs", 9 | "noEmitOnError": true, 10 | "noFallthroughCasesInSwitch": true, 11 | "noImplicitReturns": true, 12 | "noUnusedLocals": true, 13 | "pretty": true, 14 | "sourceMap": true, 15 | "strict": true, 16 | "strictNullChecks": true, 17 | "target": "es2017", 18 | "incremental": true, 19 | "rootDir": ".", 20 | "outDir": "build" 21 | }, 22 | "include": [ 23 | "src/**/*.ts", 24 | "test/**/*.ts" 25 | ], 26 | "exclude": [ 27 | "node_modules" 28 | ] 29 | } 30 | --------------------------------------------------------------------------------