Skip to content

Commit

Permalink
add span hooks for web framework integrations (#351)
Browse files Browse the repository at this point in the history
  • Loading branch information
rochdev authored Nov 5, 2018
1 parent 996aa4e commit 2034878
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
19 changes: 16 additions & 3 deletions src/plugins/util/web.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ const web = {
normalizeConfig (config) {
const headers = getHeadersToRecord(config)
const validateStatus = getStatusValidator(config)
const hooks = getHooks(config)

return Object.assign({}, config, {
headers,
validateStatus
validateStatus,
hooks
})
},

Expand Down Expand Up @@ -78,6 +80,7 @@ const web = {
span: null,
scope: null,
paths: [],
hooks: [],
beforeEnd: []
}
})
Expand All @@ -90,6 +93,8 @@ const web = {
}

function startSpan (tracer, config, req, res, name) {
req._datadog.hooks.push(config.hooks)

if (req._datadog.span) {
req._datadog.span.context().name = name
return req._datadog.span
Expand All @@ -110,11 +115,12 @@ function startSpan (tracer, config, req, res, name) {
return span
}

function finish (req) {
function finish (req, res) {
if (req._datadog.finished) return

addResponseTags(req)

req._datadog.hooks.forEach(hooks => hooks.request(req._datadog.span, req, res))
req._datadog.span.finish()
req._datadog.scope && req._datadog.scope.close()
req._datadog.finished = true
Expand All @@ -129,7 +135,7 @@ function wrapEnd (req) {

const returnValue = end.apply(this, arguments)

finish(req)
finish(req, res)

return returnValue
}
Expand Down Expand Up @@ -212,4 +218,11 @@ function getStatusValidator (config) {
return code => code < 500
}

function getHooks (config) {
const noop = () => {}
const request = (config.hooks && config.hooks.request) || noop

return { request }
}

module.exports = web
22 changes: 21 additions & 1 deletion test/plugins/util/web.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe('plugins/util/web', () => {
res = {
end
}
config = {}
config = { hooks: {} }

tracer = require('../../..').init({ plugins: false })
web = require('../../../src/plugins/util/web')
Expand Down Expand Up @@ -216,6 +216,26 @@ describe('plugins/util/web', () => {
[HTTP_ROUTE]: '/custom/route'
})
})

it('should execute the request end hook', () => {
config.hooks.request = sinon.spy()

res.end()

expect(config.hooks.request).to.have.been.calledWith(span, req, res)
})

it('should execute multiple end hooks', () => {
config.hooks = {
request: sinon.spy()
}

span = web.instrument(tracer, config, req, res, 'test.request')

res.end()

expect(config.hooks.request).to.have.been.calledWith(span, req, res)
})
})
})

Expand Down

0 comments on commit 2034878

Please sign in to comment.