Skip to content

Commit

Permalink
remove several unnecessary dependencies in the browser (#797)
Browse files Browse the repository at this point in the history
  • Loading branch information
rochdev authored Jan 29, 2020
1 parent d0d2e9b commit 2da2ceb
Show file tree
Hide file tree
Showing 13 changed files with 80 additions and 45 deletions.
4 changes: 1 addition & 3 deletions LICENSE-3rdparty.csv
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
Component,Origin,License,Copyright
require,@types/node,MIT,Copyright Authors
require,bowser,MIT,Copyright 2015 Dustin Diaz
require,container-info,MIT,Copyright 2018 Stephen Belanger
require,core-js,MIT,Copyright 2014-2020 Denis Pushkarev
require,hdr-histogram-js,BSD-2-Clause,Copyright 2016 Alexandre Victoor
require,int64-buffer,MIT,Copyright 2015-2016 Yusuke Kawasaki
require,koalas,MIT,Copyright 2013-2017 Brian Woodward
require,limiter,MIT,Copyright 2011 John Hurliman
require,lodash.kebabcase,MIT,Copyright JS Foundation and other contributors
require,lodash.memoize,MIT,Copyright JS Foundation and other contributors
require,lodash.pick,MIT,Copyright JS Foundation and other contributors
require,lodash.sortby,MIT,Copyright JS Foundation and other contributors
require,lodash.truncate,MIT,Copyright JS Foundation and other contributors
require,lodash.uniq,MIT,Copyright JS Foundation and other contributors
require,methods,MIT,Copyright 2013-2014 TJ Holowaychuk
require,module-details-from-path,MIT,Copyright 2016 Thomas Watson Steen
Expand Down
4 changes: 1 addition & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,15 @@
},
"dependencies": {
"@types/node": "^10.12.18",
"bowser": "^2.5.3",
"container-info": "^1.0.1",
"core-js": "^3.6.0",
"hdr-histogram-js": "^1.1.4",
"int64-buffer": "^0.1.9",
"koalas": "^1.0.2",
"limiter": "^1.1.4",
"lodash.kebabcase": "^4.1.1",
"lodash.memoize": "^4.1.2",
"lodash.pick": "^4.4.0",
"lodash.sortby": "^4.7.0",
"lodash.truncate": "^4.4.2",
"lodash.uniq": "^4.5.0",
"methods": "^1.1.2",
"module-details-from-path": "^1.0.3",
Expand Down
1 change: 1 addition & 0 deletions packages/datadog-plugin-fetch/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict'

const URL = require('url-parse')
const { Reference, REFERENCE_CHILD_OF } = require('opentracing')
const { REFERENCE_NOOP } = require('../../dd-trace/src/constants')
const tx = require('../../dd-trace/src/plugins/util/http')
Expand Down
1 change: 1 addition & 0 deletions packages/datadog-plugin-xmlhttprequest/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict'

const URL = require('url-parse')
const { Reference, REFERENCE_CHILD_OF } = require('opentracing')
const { REFERENCE_NOOP } = require('../../dd-trace/src/constants')
const tx = require('../../dd-trace/src/plugins/util/http')
Expand Down
5 changes: 4 additions & 1 deletion packages/dd-trace/browser.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
'use strict'

require('whatwg-fetch') // TODO: remove depenency
require('core-js/stable/object/assign') // TODO: remove dependency
require('core-js/stable/set') // TODO: remove dependency
require('core-js/stable/map') // TODO: remove dependency
require('core-js/stable/typed-array') // TODO: remove dependency

const platform = require('./src/platform')
const browser = require('./src/platform/browser')
Expand Down
24 changes: 16 additions & 8 deletions packages/dd-trace/src/exporters/browser/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,27 @@ class BrowserExporter {
this._flushing = true

const url = `${this._url.href}/v1/input/${this._clientToken}`
const method = 'POST'
const body = this._queue.join(DELIMITER)
const keepalive = true
const mode = 'no-cors'
const done = () => {
this._flushing = false
}

this._queue = []
this._size = 0

window.fetch(url, { body, method, keepalive, mode })
.then(done, done)
send(url, body, () => {
this._flushing = false
})
}
}

function send (url, body, callback) {
if (window.fetch) {
window.fetch(url, { body, method: 'POST', keepalive: true, mode: 'no-cors' })
.then(callback, callback)
} else {
const req = new XMLHttpRequest()

req.open('POST', url, true)
req.addEventListener('loadend', callback)
req.send(body)
}
}

Expand Down
7 changes: 4 additions & 3 deletions packages/dd-trace/src/id.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ if (platform.crypto) {
platform.crypto.getRandomValues(seed)
}

const map = Array.prototype.map
const pad = byte => `${byte < 16 ? '0' : ''}${byte.toString(16)}`

// Internal representation of a trace or span ID.
class Identifier {
constructor (value, radix) {
Expand Down Expand Up @@ -113,9 +116,7 @@ function toNumberString (buffer, radix) {

// Convert a buffer to a hexadecimal string.
function toHexString (buffer) {
return Array.from(buffer)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('')
return map.call(buffer, pad).join('')
}

// Simple pseudo-random 64-bit ID generator.
Expand Down
15 changes: 13 additions & 2 deletions packages/dd-trace/src/log.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
'use strict'

const memoize = require('lodash.memoize')

const _default = {
debug: message => console.log(message), /* eslint-disable-line no-console */
error: err => console.error(err) /* eslint-disable-line no-console */
Expand Down Expand Up @@ -32,6 +30,19 @@ const _checkLogLevel = (logLevel) => {
return _logLevels[_defaultLogLevel]
}

const memoize = func => {
const cache = {}
const memoized = function (key) {
if (!cache[key]) {
cache[key] = func.apply(this, arguments)
}

return cache[key]
}

return memoized
}

const log = {
use (logger) {
if (logger && logger.debug instanceof Function && logger.error instanceof Function) {
Expand Down
7 changes: 5 additions & 2 deletions packages/dd-trace/src/opentracing/span.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

const opentracing = require('opentracing')
const Span = opentracing.Span
const truncate = require('lodash.truncate')
const SpanContext = require('./span_context')
const platform = require('../platform')
const constants = require('../constants')
Expand Down Expand Up @@ -39,13 +38,17 @@ class DatadogSpan extends Span {

toString () {
const spanContext = this.context()
const resourceName = spanContext._tags['resource.name']
const resource = resourceName.length > 100
? `${resourceName.substring(0, 97)}...`
: resourceName
const json = JSON.stringify({
traceId: spanContext._traceId,
spanId: spanContext._spanId,
parentId: spanContext._parentId,
service: spanContext._tags['service.name'],
name: spanContext._name,
resource: truncate(spanContext._tags['resource.name'], { length: 100 })
resource
})

return `Span${json}`
Expand Down
5 changes: 1 addition & 4 deletions packages/dd-trace/src/platform/browser/tags.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
'use strict'

const bowser = require('bowser/bundled')
const navigator = bowser.parse(window.navigator.userAgent)

module.exports = () => {
const rum = window.DD_RUM
const context = rum && rum.getInternalContext && rum.getInternalContext()

return { navigator, ...context }
return { ...context }
}
21 changes: 12 additions & 9 deletions packages/dd-trace/src/priority_sampler.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,6 @@ const AUTO_KEEP = ext.priority.AUTO_KEEP
const USER_KEEP = ext.priority.USER_KEEP
const DEFAULT_KEY = 'service:,env:'

const priorities = new Set([
USER_REJECT,
AUTO_REJECT,
AUTO_KEEP,
USER_KEEP
])

class PrioritySampler {
constructor (env, { sampleRate, rateLimit = 100, rules = [] } = {}) {
this._env = env
Expand Down Expand Up @@ -76,7 +69,15 @@ class PrioritySampler {
}

validate (samplingPriority) {
return priorities.has(samplingPriority)
switch (samplingPriority) {
case USER_REJECT:
case USER_KEEP:
case AUTO_REJECT:
case AUTO_KEEP:
return true
default:
return false
}
}

_getContext (span) {
Expand Down Expand Up @@ -131,7 +132,9 @@ class PrioritySampler {
}

_findRule (context) {
return this._rules.find(rule => this._matchRule(context, rule))
for (let i = 0, l = this._rules.length; i < l; i++) {
if (this._matchRule(context, this._rules[i])) return this._rules[i]
}
}

_matchRule (context, rule) {
Expand Down
27 changes: 21 additions & 6 deletions packages/dd-trace/test/browser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const createEvent = (name) => {

describe('dd-trace', () => {
let tracer
let fetch

beforeEach(() => {
tracer = window.ddtrace.tracer
Expand All @@ -21,19 +22,33 @@ describe('dd-trace', () => {
})
})

afterEach(() => {
window.fetch.restore && window.fetch.restore()
})
if (window.fetch) {
beforeEach(() => {
fetch = sinon.stub(window, 'fetch').returns({
then: resolve => resolve()
})
})

it('should record and send a trace to the agent', () => {
sinon.stub(window, 'fetch').returns(Promise.resolve())
afterEach(() => {
window.fetch && window.fetch.restore()
})
} else {
beforeEach(() => {
fetch = sinon.stub(window.XMLHttpRequest.prototype, 'send')
})

afterEach(() => {
window.XMLHttpRequest.prototype.restore && window.XMLHttpRequest.prototype.restore()
})
}

it('should record and send a trace to the agent', () => {
const span = tracer.startSpan('test.request')

span.finish()

window.dispatchEvent(createEvent('visibilitychange'))

expect(window.fetch).to.have.been.called
window.fetch && expect(fetch).to.have.been.called
})
})
4 changes: 0 additions & 4 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@ const base = {
'dd-trace': './browser.js'
},
module: {
noParse: [
/node_modules\/zone\.js/,
/node_modules\/bowser/
],
rules: [{
loader: 'babel-loader'
}]
Expand Down

0 comments on commit 2da2ceb

Please sign in to comment.