Skip to content

Commit

Permalink
Merge pull request #187 from newrelic/NR-180866/performance-one-wrapp…
Browse files Browse the repository at this point in the history
…er-file

fix: Refactored wrapper to load and wrap handler early
  • Loading branch information
mrickard authored Nov 28, 2023
2 parents 4c9d718 + 5bc19db commit 9a96826
Show file tree
Hide file tree
Showing 10 changed files with 314 additions and 210 deletions.
39 changes: 20 additions & 19 deletions nodejs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,44 +102,45 @@ function validateHandlerDefinition(userHandler, handlerName, moduleName) {
}
}

async function importHandler() {
const { LAMBDA_TASK_ROOT = '.' } = process.env
const { moduleToImport, handlerToWrap } = getHandlerPath()
let wrappedHandler
let patchedHandlerPromise

const { LAMBDA_TASK_ROOT = '.' } = process.env
const { moduleToImport, handlerToWrap } = getHandlerPath()

if (process.env.NEW_RELIC_USE_ESM === 'true') {
patchedHandlerPromise = getHandler().then(userHandler => {
return newrelic.setLambdaHandler(userHandler)
})
} else {
wrappedHandler = newrelic.setLambdaHandler(getHandlerSync())
}

async function getHandler() {
const userHandler = (await getModuleWithImport(LAMBDA_TASK_ROOT, moduleToImport))[handlerToWrap]
validateHandlerDefinition(userHandler, handlerToWrap, moduleToImport)

return userHandler
}

function requireHandler() {
const { LAMBDA_TASK_ROOT = '.' } = process.env
const { moduleToImport, handlerToWrap } = getHandlerPath()

function getHandlerSync() {
const userHandler = getModuleWithRequire(LAMBDA_TASK_ROOT, moduleToImport)[handlerToWrap]
validateHandlerDefinition(userHandler, handlerToWrap, moduleToImport)

return userHandler
}


async function patchESModuleHandler() {
const userHandler = await importHandler()
const wrappedHandler = newrelic.setLambdaHandler(userHandler)
async function patchHandler() {
const args = Array.prototype.slice.call(arguments)

return wrappedHandler.apply(this, args)
return patchedHandlerPromise
.then(_wrappedHandler => _wrappedHandler.apply(this, args))
}

function patchCommonJSHandler() {
const userHandler = requireHandler()
const wrappedHandler = newrelic.setLambdaHandler(userHandler)
function patchHandlerSync() {
const args = Array.prototype.slice.call(arguments)

return wrappedHandler.apply(this, args)
}

module.exports = {
handler: process.env.NEW_RELIC_USE_ESM === 'true' ? patchESModuleHandler : patchCommonJSHandler,
handler: process.env.NEW_RELIC_USE_ESM === 'true' ? patchHandler : patchHandlerSync,
getHandlerPath
}
156 changes: 87 additions & 69 deletions nodejs/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 9a96826

Please sign in to comment.