Skip to content

Commit

Permalink
fix: Added defensive code in shim to prevent crashing when checking p…
Browse files Browse the repository at this point in the history
…arent segment (newrelic#2898)
  • Loading branch information
bizob2828 authored Jan 23, 2025
1 parent dce9deb commit 751eb96
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/shim/shim.js
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,7 @@ function recordWrapper({ shim, fn, name, recordNamer }) {
return fnApply.call(fn, this, args)
}

// middleweare recorders pass in parent segment
// middleware recorders pass in parent segment
// we need to destructure this as it is not needed past this function
// and will overwhelm trace level loggers with logging the entire spec
const { parent: specParent, ...segDesc } = spec
Expand All @@ -686,7 +686,7 @@ function recordWrapper({ shim, fn, name, recordNamer }) {
const transaction = context.transaction
const parent = transaction?.isActive() && specParent ? specParent : context.segment

if (!transaction?.isActive()) {
if (!transaction?.isActive() || !parent) {
shim.logger.debug('Not recording function %s, not in a transaction.', name)
return fnApply.call(fn, this, arguments)
}
Expand Down
18 changes: 17 additions & 1 deletion test/unit/shim/shim.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1609,7 +1609,7 @@ test('Shim', async function (t) {
})
})

await t.test('#record wrapper when called with an inactive transaction', async function (t) {
await t.test('#record wrapper should not create a new segment when called with an inactive transaction', async function (t) {
t.beforeEach(beforeEach)
t.afterEach(afterEach)
await t.test('should not create a segment', function (t, end) {
Expand All @@ -1627,6 +1627,22 @@ test('Shim', async function (t) {
})
})

await t.test('#record wrapper should not create a new segment when there is no current active segment', function (t, end) {
const { agent, shim, wrappable } = t.nr
shim.record(wrappable, 'getActiveSegment', function () {
return new RecorderSpec({ name: 'test segment' })
})

helper.runInTransaction(agent, function (tx) {
shim.setActiveSegment(null)
const segment = wrappable.getActiveSegment()
assert.equal(segment, null)
tx.end()
assert.equal(tx.isActive(), false)
end()
})
})

await t.test('should execute the wrapped function', function (t, end) {
const { agent, shim } = t.nr
let executed = false
Expand Down

0 comments on commit 751eb96

Please sign in to comment.