├── .npmignore ├── .eslintignore ├── src ├── index.js ├── wrapper.js └── tracer.js ├── .gitignore ├── .github └── workflows │ └── release.yml ├── workflows └── release.yml ├── LICENSE ├── .eslintrc ├── package.json ├── README.md └── CODE_OF_CONDUCT.md /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | **/node_modules/** 2 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | export * from './tracer'; 2 | export * from './wrapper'; 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | **node_modules/ 3 | **dist/ 4 | **/.DS_Store 5 | .vscode 6 | .env 7 | *.cpuprofile 8 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | release: 8 | name: Release 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v2 13 | with: 14 | fetch-depth: 0 15 | - name: Setup Node.js 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: 12 19 | 20 | - name: Install dependencies @epsagon/cloudflare 21 | run: npm install && npm run build 22 | 23 | - name: Release @epsagon/cloudflare 24 | env: 25 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 26 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 27 | run: npm run semantic-release 28 | -------------------------------------------------------------------------------- /workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | release: 8 | name: Release 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v2 13 | with: 14 | fetch-depth: 0 15 | - name: Setup Node.js 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: 12 19 | 20 | - name: Install dependencies @epsagon/cloudflare 21 | run: npm install && npm run build 22 | 23 | # - name: Release @epsagon/cloudflare 24 | # env: 25 | # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 26 | # NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 27 | # run: npm run semantic-release 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Epsagon 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb", 3 | "env": { 4 | "node": true, 5 | "browser": true 6 | }, 7 | "plugins": [ 8 | "json" 9 | ], 10 | "rules": { 11 | "no-console": "off", 12 | "no-restricted-syntax": "off", 13 | "import/no-named-as-default": "off", 14 | "no-new": "off", 15 | "indent": ["error", 4], 16 | "function-paren-newline": ["error", "consistent"], 17 | "require-jsdoc": ["error", { 18 | "require": { 19 | "FunctionDeclaration": true, 20 | "MethodDefinition": true, 21 | "ClassDeclaration": true, 22 | "ArrowFunctionExpression": false, 23 | "FunctionExpression": true 24 | } 25 | }], 26 | "operator-linebreak": ["error", "after"], 27 | "valid-jsdoc": ["error", { 28 | "requireReturn": false 29 | }], 30 | "comma-dangle": ["error", { 31 | "arrays": "always-multiline", 32 | "objects": "always-multiline", 33 | "imports": "never", 34 | "exports": "never", 35 | "functions": "never" 36 | }] 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@epsagon/cloudflare", 3 | "version": "0.0.0-development", 4 | "description": "This package provides tracing to Cloudflare workers for the collection of distributed tracing and performance metrics.", 5 | "main": "dist/index.js", 6 | "module": "dist/index.modern.js", 7 | "source": "src/index.js", 8 | "scripts": { 9 | "build": "microbundle --no-compress --format modern,cjs", 10 | "dev": "microbundle watch --no-compress --format modern,cjs", 11 | "lint:js": "eslint --max-warnings=0 ./src/ -f table --ext .js --ext .jsx", 12 | "lint:js:fix": "eslint --max-warnings=0 ./src/ -f table --ext .js --ext .jsx --fix", 13 | "lint": "npm run lint:js", 14 | "semantic-release": "semantic-release" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/epsagon/epsagon-cloudflare.git" 19 | }, 20 | "keywords": [ 21 | "browser tracing", 22 | "epsagon", 23 | "tracing", 24 | "distributed-tracing", 25 | "cloudflare", 26 | "cloudflare workers", 27 | "debugging", 28 | "monitoring" 29 | ], 30 | "author": "Epsagon Team ", 31 | "license": "MIT", 32 | "bugs": { 33 | "url": "https://github.com/epsagon/epsagon-cloudflare/issues" 34 | }, 35 | "homepage": "https://github.com/epsagon/epsagon-cloudflare#readme", 36 | "devDependencies": { 37 | "eslint": "^4.18.0", 38 | "eslint-config-airbnb": "^17.1.0", 39 | "eslint-plugin-chai-friendly": "^0.4.1", 40 | "eslint-plugin-import": "^2.14.0", 41 | "eslint-plugin-json": "^1.2.1", 42 | "eslint-plugin-jsx-a11y": "^6.1.1", 43 | "eslint-plugin-mocha": "^4.11.0", 44 | "eslint-plugin-react": "^7.11.0", 45 | "microbundle": "^0.13.3", 46 | "semantic-release": "^17.4.4" 47 | }, 48 | "dependencies": { 49 | "uuid": "^8.3.2", 50 | "uuid-parse": "^1.1.0" 51 | }, 52 | "release": { 53 | "branches": [ 54 | "main" 55 | ] 56 | }, 57 | "files": [ 58 | "dist" 59 | ], 60 | "publishConfig": { 61 | "access": "public" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |

3 | 4 | 5 | 6 |
7 |

8 | 9 | # Epsagon Tracing for Cloudflare Workers 10 | 11 | This package provides tracing to Cloudflare Workers for the collection of distributed tracing and performance metrics in [Epsagon](https://app.epsagon.com/?utm_source=github). 12 | 13 | 14 | 15 | ## Contents 16 | 17 | - [Installation](#installation) 18 | - [Usage](#usage) 19 | - [Tracing Fetch Requests](#tracing-fetch-requests) 20 | 21 | 22 | ### Installation 23 | 24 | Installation is done via the usual `npm install @epsagon/cloudflare`. 25 | 26 | ### Usage 27 | 28 | To configure the package, you need to wrap your listener with the epsagon agent. So if your current code looks something like this: 29 | 30 | ```javascript 31 | addEventListener('fetch', (event) => { 32 | event.respondWith(handleRequest(event.request)) 33 | }) 34 | 35 | function handleRequest(request) { 36 | //your worker code. 37 | } 38 | ``` 39 | 40 | You can change that to: 41 | 42 | ```javascript 43 | import { epsagon } from '@epsagon/cloudflare' 44 | 45 | const epsagon_config = { 46 | token: 'epsagon-token', 47 | app_name: 'application-name', 48 | } 49 | 50 | const listener = epsagon(epsagon_config, (event) => { 51 | event.respondWith(handleRequest(event.request)) 52 | }) 53 | 54 | addEventListener('fetch', listener) 55 | 56 | function handleRequest(request) { 57 | //your worker code. 58 | } 59 | ``` 60 | 61 | ### Tracing Fetch Requests 62 | 63 | To be able to associate the a subrequest with the correct incoming request, you will have to use the fetch defined on the tracer described above. The method on the tracer delegates all arguments to the regular fetch method, so the `tracer.fetch` function is a drop-in replacement for all `fetch` function calls. 64 | 65 | Example: 66 | 67 | ```typescript 68 | async function handleRequest(request) { 69 | return request.tracer.fetch('link') 70 | } 71 | ``` 72 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at dev@epsagon.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /src/wrapper.js: -------------------------------------------------------------------------------- 1 | import Tracer from './tracer'; 2 | 3 | /** 4 | * Represents promise coordinator, ensures all promises are settled before 5 | * sending events to be formatted and sent to tracer. 6 | */ 7 | export class PromiseSettledCoordinator { 8 | /** 9 | * @param {function} finished function that runs after all promises are settled. 10 | */ 11 | constructor(finished) { 12 | this.finished = finished; 13 | this.promises = []; 14 | this.allSettled = false; 15 | } 16 | 17 | /** 18 | * Adds a promise to be settled 19 | * @param {Promise} promise that needs to be settled. 20 | */ 21 | addPromise(promise) { 22 | if (this.allSettled) { 23 | throw Error('All promises have already been settled!'); 24 | } 25 | this.promises.push(promise); 26 | const currentLength = this.promises.length; 27 | const settled = Promise.allSettled(this.promises); 28 | settled.then((results) => { 29 | if (currentLength === this.promises.length) { 30 | this.allSettled = true; 31 | this.finished(results); 32 | } 33 | }); 34 | } 35 | } 36 | 37 | /** 38 | * Represents wrapper used for instrumentation 39 | */ 40 | class TraceWrapper { 41 | /** 42 | * @param {object} event the cloudflare event data. 43 | * @param {function} listener that wraps instrumented function. 44 | * @param {object} config tracer configuration 45 | */ 46 | constructor(event, listener, config) { 47 | this.event = event; 48 | this.listener = listener; 49 | this.waitUntilUsed = false; 50 | this.config = config; 51 | this.tracer = new Tracer(event.request, this.config); 52 | this.waitUntilSpan = this.tracer.startChildSpan('waitUntil', 'worker'); 53 | this.settler = new PromiseSettledCoordinator(() => { 54 | this.waitUntilSpan.finish(); 55 | this.sendEvents(); 56 | }); 57 | this.setupWaitUntil(); 58 | this.setUpRespondWith(); 59 | } 60 | 61 | /** 62 | * Sends events to tracer, filtering out those being waited on 63 | */ 64 | async sendEvents() { 65 | const excludes = this.waitUntilUsed ? [] : ['waitUntil']; 66 | await this.tracer.sendEvents(excludes); 67 | this.waitUntilResolve(); 68 | } 69 | 70 | /** 71 | * Starts wait until process 72 | */ 73 | startWaitUntil() { 74 | this.waitUntilUsed = true; 75 | this.waitUntilSpan.start(); 76 | } 77 | 78 | /** 79 | * Finishes wait until process, adds exception data as necessary 80 | * @param {object} error captured during request, sent to tracer 81 | */ 82 | finishWaitUntil(error) { 83 | if (error) { 84 | this.tracer.addData({ exception: true, waitUtilException: error.toString() }); 85 | this.waitUntilSpan.addData({ exception: error }); 86 | if (error.stack) this.waitUntilSpan.addData({ stacktrace: error.stack }); 87 | } 88 | } 89 | 90 | /** 91 | * Sets up wait until process 92 | */ 93 | setupWaitUntil() { 94 | const waitUntilPromise = new Promise((resolver) => { 95 | this.waitUntilResolve = resolver; 96 | }); 97 | this.event.waitUntil(waitUntilPromise); 98 | this.proxyWaitUntil(); 99 | } 100 | 101 | /** 102 | * Adds proxy to wait until process 103 | */ 104 | proxyWaitUntil() { 105 | const logger = this; 106 | this.event.waitUntil = new Proxy(this.event.waitUntil, { 107 | /** 108 | * Trap and modify incoming request 109 | * @param {function} _target function. 110 | * @param {object} _thisArg the this argument for the call. 111 | * @param {object} argArray list of arguments for the call. 112 | */ 113 | apply(_target, _thisArg, argArray) { 114 | logger.startWaitUntil(); 115 | const promise = Promise.resolve(argArray[0]); 116 | promise.then(() => { 117 | }); 118 | logger.settler.addPromise(promise); 119 | promise 120 | .then(() => { 121 | logger.finishWaitUntil(); 122 | }) 123 | .catch((reason) => { 124 | logger.finishWaitUntil(reason); 125 | }); 126 | }, 127 | }); 128 | } 129 | 130 | /** 131 | * Set up respond with process 132 | */ 133 | setUpRespondWith() { 134 | this.proxyRespondWith(); 135 | try { 136 | this.event.request.tracer = this.tracer; 137 | this.event.waitUntilTracer = this.waitUntilSpan; 138 | this.listener(this.event); 139 | } catch (err) { 140 | this.tracer.finishResponse(undefined, err); 141 | } 142 | } 143 | 144 | /** 145 | * Adds proxy to respond with process 146 | */ 147 | proxyRespondWith() { 148 | const logger = this; 149 | this.event.respondWith = new Proxy(this.event.respondWith, { 150 | /** 151 | * Trap and modify incoming request 152 | * @param {function} target function. 153 | * @param {object} thisArg the this argument for the call. 154 | * @param {object} argArray list of arguments for the call. 155 | */ 156 | apply(target, thisArg, argArray) { 157 | const responsePromise = Promise.resolve(argArray[0]); 158 | Reflect.apply(target, thisArg, argArray); 159 | const promise = new Promise((resolver, reject) => { 160 | responsePromise 161 | .then((response) => { 162 | let responseBody; 163 | let clonedResponse; 164 | const contentType = response.headers.get('content-type'); 165 | if (contentType && contentType.indexOf('application/json') !== -1) { 166 | clonedResponse = response.clone(); 167 | clonedResponse.json().then((data) => { 168 | responseBody = data; 169 | }); 170 | } 171 | if (contentType && contentType.indexOf('text/plain;charset=UTF-8') !== -1) { 172 | clonedResponse = response.clone(); 173 | clonedResponse.text().then((data) => { 174 | responseBody = data; 175 | }); 176 | } 177 | setTimeout(() => { 178 | logger.tracer.finishResponse(response, null, responseBody); 179 | resolver(response); 180 | }, 1); 181 | }).catch((reason) => { 182 | setTimeout(() => { 183 | logger.tracer.finishResponse(undefined, reason); 184 | reject(reason); 185 | }, 1); 186 | }); 187 | }); 188 | logger.settler.addPromise(promise); 189 | }, 190 | }); 191 | } 192 | } 193 | 194 | /** 195 | * Initiates tracer configuration based on user defined config and defaults. 196 | * @param {object} cfg user defined configuration options. 197 | * @returns {object} config to be used by tracer. 198 | */ 199 | function resolve(cfg) { 200 | const configDefaults = { 201 | acceptTraceContext: false, 202 | token: '', 203 | app_name: 'cloudflare', 204 | data: {}, 205 | redactRequestHeaders: ['authorization', 'cookie', 'referer'], 206 | redactResponseHeaders: ['set-cookie'], 207 | sampleRates: () => 1, 208 | sendTraceContext: false, 209 | serviceName: 'worker', 210 | debug: false, 211 | }; 212 | 213 | const config = Object.assign({}, configDefaults, cfg); 214 | config.redactRequestHeaders = config.redactRequestHeaders.map(header => header.toLowerCase()); 215 | config.redactResponseHeaders = config.redactResponseHeaders.map(header => header.toLowerCase()); 216 | return config; 217 | } 218 | 219 | /** 220 | * Main function, used as wrapper for instrumentation 221 | * @param {object} cfg user defined configuration options. 222 | * @param {function} listener from cloudflare worker, to be modified for tracing support. 223 | * @returns {Proxy} modified listener that is used to capture trace data. 224 | */ 225 | export function epsagon(cfg, listener) { 226 | const config = resolve(cfg); 227 | return new Proxy(listener, { 228 | /** 229 | * Trap and modify incoming request 230 | * @param {function} _target function. 231 | * @param {object} _thisArg the this argument for the call. 232 | * @param {object} argArray list of arguments for the call. 233 | */ 234 | apply(_target, _thisArg, argArray) { 235 | const event = argArray[0]; 236 | new TraceWrapper(event, listener, config); 237 | }, 238 | }); 239 | } 240 | -------------------------------------------------------------------------------- /src/tracer.js: -------------------------------------------------------------------------------- 1 | const uuid = require('uuid'); 2 | const uuidParse = require('uuid-parse'); 3 | 4 | /** 5 | * Return UUID in hex string. 6 | * @param {string} id uuid object. 7 | * @returns {string} UUID in hex. 8 | */ 9 | function UUIDToHex(id) { 10 | const uuidBuffer = Buffer.alloc(16); 11 | uuidParse.parse(id, uuidBuffer); 12 | return uuidBuffer.toString('hex'); 13 | } 14 | 15 | /** 16 | * Return redacted headers. 17 | * @param {object} from the request or response headers. 18 | * @param {array} redacted array of header keys to redact. 19 | * @returns {object} redacted request or response headers. 20 | */ 21 | const convertHeaders = (from, redacted) => { 22 | const to = {}; 23 | for (const [key, value] of from.entries()) { 24 | const lowerKey = key.toLowerCase(); 25 | to[lowerKey] = redacted.includes(lowerKey) ? 'REDACTED' : value; 26 | } 27 | return to; 28 | }; 29 | 30 | /** 31 | * Represents a span. 32 | */ 33 | class Span { 34 | /** 35 | * @param {object} init contains name of span. 36 | * @param {object} config tracer configuration object. 37 | */ 38 | constructor(init, config) { 39 | this.config = config; 40 | this.data = {}; 41 | this.childSpans = []; 42 | this.eventMeta = { 43 | timestamp: Date.now(), 44 | name: init.name, 45 | trace: init.trace_context, 46 | }; 47 | } 48 | 49 | /** 50 | * Parse all events captured into a single array 51 | * @returns {array} events array. 52 | */ 53 | parseToEvents() { 54 | const event = Object.assign({}, this.data, this.eventMeta); 55 | const childEvents = this.childSpans.map(span => span.parseToEvents()).flat(1); 56 | return [event, ...childEvents]; 57 | } 58 | 59 | /** 60 | * Function to add data to arbitrary data to tracer. 61 | * @param {object} data to add to tracer. 62 | */ 63 | addData(data) { 64 | Object.assign(this.data, data); 65 | } 66 | 67 | /** 68 | * Transform request into event data, add event to tracer. 69 | * @param {object} request data to transform and add to tracer. 70 | */ 71 | addRequest(request) { 72 | this.request = request; 73 | if (!request) return; 74 | 75 | const json = { 76 | headers: request.headers ? 77 | convertHeaders(request.headers, this.config.redactRequestHeaders) : undefined, 78 | method: request.method, 79 | redirect: request.redirect, 80 | referrer: request.referrer, 81 | referrerPolicy: request.referrerPolicy, 82 | url: request.url, 83 | }; 84 | this.addData({ request: json }); 85 | } 86 | 87 | /** 88 | * Transform response into event data, add event to tracer. 89 | * @param {object} response data to transform and add to tracer. 90 | * @param {object} body optional body that can be passed for inclusion. 91 | */ 92 | addResponse(response, body) { 93 | this.response = response; 94 | if (!response) return; 95 | const json = { 96 | headers: response.headers ? 97 | convertHeaders(response.headers, this.config.redactResponseHeaders) : undefined, 98 | ok: response.ok, 99 | redirected: response.redirected, 100 | status: response.status, 101 | statusText: response.statusText, 102 | url: response.url, 103 | }; 104 | const contentType = this.response.headers.get('content-type'); 105 | if (body) { 106 | json.body = body; 107 | this.addData({ response: json }); 108 | } else { 109 | if (contentType && contentType.indexOf('application/json') !== -1) { 110 | this.response.json().then((data) => { 111 | json.body = data; 112 | this.addData({ response: json }); 113 | }); 114 | } 115 | if (contentType && contentType.indexOf('text/plain;charset=UTF-8') !== -1) { 116 | this.response.text().then((data) => { 117 | json.body = data; 118 | this.addData({ response: json }); 119 | }); 120 | } 121 | if (contentType && contentType.indexOf('text/html; charset=UTF-8') !== -1) { 122 | this.addData({ response: json }); 123 | } 124 | } 125 | } 126 | 127 | /** 128 | * Add log data to tracer 129 | * @param {string} message to be added as log. 130 | */ 131 | log(message) { 132 | this.data.logs = this.data.logs || []; 133 | this.data.logs.push(`${new Date().toISOString()}: ${message}`); 134 | } 135 | 136 | /** 137 | * Calculate tracer start time. 138 | */ 139 | start() { 140 | this.eventMeta.timestamp = Date.now(); 141 | } 142 | 143 | /** 144 | * Calculate tracer end time. 145 | */ 146 | finish() { 147 | this.eventMeta.duration_ms = Date.now() - this.eventMeta.timestamp; 148 | } 149 | 150 | /** 151 | * Replacement fetch that intercepts and captures request and response data. 152 | * @param {string} input url to fetch. 153 | * @param {object} init object from fetch call. 154 | * @returns {Promise} the fetched promise. 155 | */ 156 | fetch(input, init) { 157 | const request = new Request(input, init); 158 | const childSpan = this.startChildSpan(request.url, 'fetch'); 159 | childSpan.addRequest(request); 160 | const promise = fetch(request); 161 | promise 162 | .then((response) => { 163 | childSpan.addResponse(response); 164 | childSpan.finish(); 165 | }) 166 | .catch((reason) => { 167 | childSpan.addData({ exception: reason }); 168 | childSpan.finish(); 169 | }); 170 | return promise; 171 | } 172 | 173 | /** 174 | * Create child span. 175 | * @param {string} name of child span. 176 | * @returns {object} the child span.. 177 | */ 178 | startChildSpan(name) { 179 | const span = new Span({ name }, this.config); 180 | this.childSpans.push(span); 181 | return span; 182 | } 183 | } 184 | 185 | /** 186 | * Represents a span. 187 | */ 188 | export class Tracer extends Span { 189 | /** 190 | * @param {object} request contains the incoming request data. 191 | * @param {object} config tracer configuration object. 192 | */ 193 | constructor(request, config) { 194 | super({ 195 | name: 'request', 196 | }, config); 197 | this.request = request; 198 | this.addRequest(request); 199 | this.addData(config.data); 200 | } 201 | 202 | /** 203 | *Parses out any spans/events that are not yet completed. 204 | * @param {array} excludeSpans list of spans with uncompleted transactions. 205 | */ 206 | async sendEvents(excludeSpans) { 207 | const events = this.parseToEvents().filter(event => (excludeSpans ? 208 | !excludeSpans.includes(event.name) : true)); 209 | await this.sendBatch(events); 210 | } 211 | 212 | /** 213 | *Takes in response data, formats according to if an error occurs, adds to tracer. 214 | * @param {object} response list of spans with uncompleted transactions. 215 | * @param {object} error object. 216 | * @param {object} body option body that can be passed for inclusion. 217 | */ 218 | finishResponse(response, error, body) { 219 | if (response) { 220 | this.addResponse(response, body); 221 | } else if (error) { 222 | this.addData({ 223 | exception: true, 224 | error_name: error.name, 225 | stack: error.stack, 226 | message: error.message, 227 | responseException: error.toString(), 228 | }); 229 | } 230 | this.finish(); 231 | } 232 | 233 | /** 234 | *Take all event data and convert into Epsagon tracer format 235 | * @param {array} events data for all spans. 236 | */ 237 | async sendBatch(events) { 238 | try { 239 | const url = 'https://us-east-1.tc.epsagon.com/'; 240 | 241 | const traces = { 242 | app_name: this.config.app_name, 243 | token: this.config.token, 244 | version: '1.0.0', 245 | platform: 'Javascript', 246 | exceptions: [], 247 | }; 248 | 249 | const triggerTrace = { 250 | origin: 'trigger', 251 | id: uuid.v4(), 252 | start_time: (events[0].timestamp * 0.001), 253 | duration: (events[0].duration_ms * 0.001), 254 | resource: { 255 | name: events[0].request.headers.host, 256 | type: 'http', 257 | operation: events[0].request.method, 258 | metadata: { 259 | 'http.request.headers': events[0].request.headers, 260 | 'http.request.path': new URL(events[0].request.url).pathname, 261 | }, 262 | }, 263 | error_code: 0, 264 | exception: {}, 265 | }; 266 | 267 | const runnerTrace = { 268 | origin: 'runner', 269 | id: uuid.v4(), 270 | start_time: (events[0].timestamp * 0.001), 271 | duration: (events[0].duration_ms * 0.001), 272 | resource: { 273 | name: (`${events[0].request.headers.host.replace('https://', '').split('.')[0]}-worker`), 274 | type: 'cloudflare_worker', 275 | operation: 'execute', 276 | metadata: { 277 | 'cloudflare.return_value': events[0].response ? events[0].response.body : null, 278 | 'cloudflare.requestContext': events[0].request, 279 | 'cloudflare.debug_events': this.config.debug ? JSON.stringify(events) : null, 280 | 'cloudflare.logs': events[0].logs || [], 281 | }, 282 | }, 283 | }; 284 | 285 | if (events[0].exception) { 286 | runnerTrace.exception = { 287 | type: events[0].error_name, 288 | tracebook: events[0].stack, 289 | additional_data: { 290 | warning: false, 291 | handled: false, 292 | }, 293 | message: events[0].message, 294 | }; 295 | runnerTrace.error_code = 2; 296 | } else { 297 | runnerTrace.exception = {}; 298 | runnerTrace.error_code = 0; 299 | } 300 | 301 | traces.events = [triggerTrace, runnerTrace]; 302 | 303 | if (events.length > 1) { 304 | events.forEach((value, index) => { 305 | if (index !== 0) { 306 | const hexTraceId = UUIDToHex(uuid.v4()); 307 | const spanId = UUIDToHex(uuid.v4()).slice(16); 308 | const parentSpanId = UUIDToHex(uuid.v4()).slice(16); 309 | const httpTrace = { 310 | origin: 'http', 311 | start_time: (value.timestamp * 0.001), 312 | duration: (value.duration_ms * 0.001), 313 | resource: { 314 | name: value.name, 315 | type: 'http', 316 | operation: value.request.method, 317 | metadata: { 318 | http_trace_id: `${hexTraceId}:${spanId}:${parentSpanId}:1`, 319 | 'http.request.path': value.name, 320 | 'http.request.headers': value.request.headers, 321 | 'http.response.body': value.response.body, 322 | 'http.response.status_code': value.response.status, 323 | 'http.url': value.response.url, 324 | }, 325 | }, 326 | error_code: 0, 327 | exception: {}, 328 | }; 329 | traces.events.push(httpTrace); 330 | } 331 | }); 332 | } 333 | const params = { 334 | method: 'POST', 335 | body: JSON.stringify(traces), 336 | headers: { 337 | 'Content-Type': 'application/json', 338 | Authorization: `Bearer ${this.config.token}`, 339 | }, 340 | }; 341 | const request = new Request(url, params); 342 | await fetch(request); 343 | } catch (error) { 344 | console.log('error in Epsagon > ', error); 345 | } 346 | } 347 | } 348 | export default Tracer; 349 | --------------------------------------------------------------------------------