Giter Site home page Giter Site logo

node-newrelic-koa's Introduction

⚠️ This package has been deprecated. The functionality has been merged into the core newrelic module.

New Relic Open Source community plus project banner.

New Relic Koa instrumentation

npm status badge koa instrumentation CI codecov

New Relic's official Koa framework instrumentation for use with the New Relic Node.js agent.

This module is a dependency of the agent and is installed by default when you install the agent.

Installation

This package is a dependency of the the Node Agent, and the average user should not need to install it manually.

For more information, please see the agent installation guide.

Getting Started

Our API and developer documentation for writing instrumentation will be of help. We particularly recommend the tutorials and various "shim" API documentation.

Usage

In addition to the Koa framework, we support additional specific routing modules.

Supported Routing Modules

  • @koa/router
  • koa-router
  • koa-route

For more information, please see the agent compatibility and requirements.

Testing

The module includes a suite of unit and functional tests which should be used to verify that your changes don't break existing functionality.

All tests are stored in tests/ and are written using Tap with the extension .tap.js.

To run the full suite, run: npm test.

Individual test scripts include:

npm run unit
npm run versioned

Support

Should you need assistance with New Relic products, you are in good hands with several support channels.

If the issue has been confirmed as a bug or is a feature request, please file a GitHub issue.

Support Channels

Privacy

At New Relic we take your privacy and the security of your information seriously, and are committed to protecting your information. We must emphasize the importance of not sharing personal data in public forums, and ask all users to scrub logs and diagnostic information for sensitive information, whether personal, proprietary, or otherwise.

We define “Personal Data” as any information relating to an identified or identifiable individual, including, for example, your name, phone number, post code or zip code, Device ID, IP address and email address.

For more information, review New Relic’s General Data Privacy Notice.

Contribute

We encourage your contributions to improve the koa instrumentation module! Keep in mind when you submit your pull request, you'll need to sign the CLA via the click-through using CLA-Assistant. You only have to sign the CLA one time per project.

If you have any questions, or to execute our corporate CLA, required if your contribution is on behalf of a company, please drop us an email at [email protected].

A note about vulnerabilities

As noted in our security policy, New Relic is committed to the privacy and security of our customers and their data. We believe that providing coordinated disclosure by security researchers and engaging with the security community are important means to achieve our security goals.

If you believe you have found a security vulnerability in this project or any of New Relic's products or websites, we welcome and greatly appreciate you reporting it to New Relic through HackerOne.

If you would like to contribute to this project, review these guidelines.

To all contributors, we thank you! Without your contribution, this project would not be what it is today. We also host a community project page dedicated to New Relic Koa (Node).

License

New Relic Koa instrumentation is licensed under the Apache 2.0 License.

New Relic Koa instrumentation also uses source code from third-party libraries. You can find full details on which libraries are used and the terms under which they are licensed in the third-party notices document.

node-newrelic-koa's People

Contributors

astormnewrelic avatar bizob2828 avatar carlo-808 avatar cesine avatar coreyarnold avatar dependabot[bot] avatar garbados avatar github-actions[bot] avatar imhunterand avatar jgeurts avatar jmartin4563 avatar jsumners-nr avatar lykkin avatar michaelgoin avatar mmfred avatar mrickard avatar nataliewolfe avatar nijotz avatar nikostoulas avatar paperclypse avatar psvet avatar shumsky avatar snyk-bot avatar svetlanabrennan avatar tangollama avatar zacanger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-newrelic-koa's Issues

Upgrade tap to version 15

Upgrade tap to version 15.

tap at v15 seems to break when running versioned tests, most likely around how an agent is started and torn down for each test.
These errors popped up when running the versioned tests:

(node:14851) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [Server]. Use emitter.setMaxListeners() to increase limit

and

                      this.agent = new Agent(config)
                      this._created = new Error('Only one agent at a time! This one was created at:')
                    ------------------^

How to enable/capture external service

Below is my app.js

require('@newrelic/koa');
import Koa from 'koa';
import koaBody from 'koa-body';

newrelic.js

'use strict'
/**
 * New Relic agent configuration.
 *
 * See lib/config/default.js in the agent distribution for a more complete
 * description of configuration variables and their potential values.
 */
exports.config = {
  /**
   * Array of application names.
   */
  app_name    : [process.env.NEW_RELIC_APP_NAME],
  /**
   * Your New Relic license key.
   */
  license_key : process.env.NODE_ENV == 'production' ? process.env.NEW_RELIC_LICENSE_KEY : process.env.NEW_RELIC_LICENSE_KEY,
  logging: {
    /**
     * Level at which to log. 'trace' is most useful to New Relic when diagnosing
     * issues with the agent, 'info' and higher will impose the least overhead on
     * production applications.
     */
    level: 'info'
  },
  /**
   * When true, all request headers except for those listed in attributes.exclude
   * will be captured for all traces, unless otherwise specified in a destination's
   * attributes include/exclude lists.
   */
  allow_all_headers: true,
  enforce_backstop: false,
  distributed_tracing: {
    enabled: true
  },
  attributes: {
    /**
     * Prefix of attributes to exclude from all destinations. Allows * as wildcard
     * at end.
     *
     * NOTE: If excluding headers, they must be in camelCase form to be filtered.
     *
     * @env NEW_RELIC_ATTRIBUTES_EXCLUDE
     */
    exclude: [
      'request.headers.cookie',
      'request.headers.authorization',
      'request.headers.proxyAuthorization',
      'request.headers.setCookie*',
      'request.headers.x*',
      'response.headers.cookie',
      'response.headers.authorization',
      'response.headers.proxyAuthorization',
      'response.headers.setCookie*',
      'response.headers.x*'
    ]
  }
}

I am not getting the external service metrics, can you please point me to the right direction, I tried reading the docs too, but couldn't find anything or understand.

Add copyright to all source files

Every source file in the repository should contain the copyright block heading on top:

/*
* Copyright 2020 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/

This includes bash scripts (slightly different commenting style) and code examples. Does not include copy-paste templates.

NOTE: we want the Apache-2.0 license to land first so these are consistent and that license is the current active for the commit(s) applying these changes.

[Repolinter] Open Source Policy Issues

Repolinter Report

🤖This issue was automatically generated by repolinter-action, developed by the Open Source and Developer Advocacy team at New Relic. This issue will be automatically updated or closed when changes are pushed. If you have any problems with this tool, please feel free to open a GitHub issue or give us a ping in #help-opensource.

This Repolinter run generated the following results:

❗ Error ❌ Fail ⚠️ Warn ✅ Pass Ignored Total
0 1 0 6 0 7

Fail #

code-of-conduct-file-does-not-exist #

New Relic has moved the CODE_OF_CONDUCT file to a centralized location where it is referenced automatically by every repository in the New Relic organization. Because of this change, any other CODE_OF_CONDUCT file in a repository is now redundant and should be removed. For more information please visit https://docs.google.com/document/d/1y644Pwi82kasNP5VPVjDV8rsmkBKclQVHFkz8pwRUtE/view. Found files. Below is a list of files or patterns that failed:

  • CODE_OF_CONDUCT.md
    • 🔨 Suggested Fix: Remove file

Passed #

Click to see rules

license-file-exists #

Found file (LICENSE). New Relic requires that all open source projects have an associated license contained within the project. This license must be permissive (e.g. non-viral or copyleft), and we recommend Apache 2.0 for most use cases. For more information please visit https://docs.google.com/document/d/1vML4aY_czsY0URu2yiP3xLAKYufNrKsc7o4kjuegpDw/edit.

readme-file-exists #

Found file (README.md). New Relic requires a README file in all projects. This README should give a general overview of the project, and should point to additional resources (security, contributing, etc.) where developers and users can learn further. For more information please visit https://github.com/newrelic/open-by-default.

readme-starts-with-community-plus-header #

The first 5 lines contain all of the requested patterns. (README.md). The README of a community plus project should have a community plus header at the start of the README. If you already have a community plus header and this rule is failing, your header may be out of date, and you should update your header with the suggested one below. For more information please visit https://opensource.newrelic.com/oss-category/.

readme-contains-link-to-security-policy #

Contains a link to the security policy for this repository (README.md). New Relic recommends putting a link to the open source security policy for your project (https://github.com/newrelic/<repo-name>/security/policy or ../../security/policy) in the README. For an example of this, please see the "a note about vulnerabilities" section of the Open By Default repository. For more information please visit https://nerdlife.datanerd.us/new-relic/security-guidelines-for-publishing-source-code.

readme-contains-discuss-topic #

Contains a link to the appropriate discuss.newrelic.com topic (README.md). New Relic recommends directly linking the your appropriate discuss.newrelic.com topic in the README, allowing developer an alternate method of getting support. For more information please visit https://nerdlife.datanerd.us/new-relic/security-guidelines-for-publishing-source-code.

third-party-notices-file-exists #

Found file (THIRD_PARTY_NOTICES.md). A THIRD_PARTY_NOTICES.md file can be present in your repository to grant attribution to all dependencies being used by this project. This document is necessary if you are using third-party source code in your project, with the exception of code referenced outside the project's compiled/bundled binary (ex. some Java projects require modules to be pre-installed in the classpath, outside the project binary and therefore outside the scope of the THIRD_PARTY_NOTICES). Please review your project's dependencies and create a THIRD_PARTY_NOTICES.md file if necessary. For JavaScript projects, you can generate this file using the oss-cli. For more information please visit https://docs.google.com/document/d/1y644Pwi82kasNP5VPVjDV8rsmkBKclQVHFkz8pwRUtE/view.

koa: Update instrumentation to construct specs at instrumentation level

Is your feature request related to a problem? Please describe.

Instrumentation using shim should instantiate the relevant spec type and not rely on the shim helpers to do this. Another indicator is the instrumentation that uses shim should no longer return object literals with various keys.

Additional context

This cannot be completely merged until the agent has a released for #2036

Error: Cannot read property 'nameState' of null

Hi, this is a bit hard for me to diagnose, so I'm hoping posting here might help uncover the root cause. We've been seeing random errors coming from what seems to be this project, but it might be more related to Koa Router... The errors have been happening for the last few weeks and they look like:

TypeError: Cannot read property 'nameState' of null
    at Object.set (/var/www/html/node_modules/@newrelic/koa/lib/instrumentation.js:94:12)
    at dispatch (/var/www/html/node_modules/@koa/router/lib/router.js:353:23)
    at wrapper (/var/www/html/node_modules/newrelic/lib/shim/shim.js:947:24)
    at dispatch (/var/www/html/node_modules/koa-compose/index.js:42:32)
    ...

We're currently running @koa/router v9.0.1, @newrelic/koa v3.0.0, koa v2.12.0, and newrelic v6.9.0 on the latest Node.js v10 LTS. I'm not sure what else I can provide or really how to reproduce this issue, but I will help however I can!

koa: drop node 14

Is your feature request related to a problem? Please describe.

  • Update package engines stanza to >=16.
  • Update versioned tests engines to remove 14

Support for newrelic >=10.0.0

Newrelic >= 10.0.0 is not supported by newrelic/koa.

    "@newrelic/koa": "=7.2.0",
    "newrelic": "=10.0.0",

node:16.11.0

nodejs-nodejs-1        | 
nodejs-nodejs-1        | > [email protected] start
nodejs-nodejs-1        | > node ./index.js
nodejs-nodejs-1        | 
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:45.736Z","msg":"Unable to find configuration file. If a configuration file is desired (common for non-containerized environments), a base configuration file can be copied from /app/node_modules/newrelic/newrelic.js and renamed to \"newrelic.js\" in the directory from which you will start your application. Attempting to start agent using environment variables."}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:45.740Z","msg":"Using New Relic for Node.js. Agent version: 10.0.0; Node version: v16.11.0."}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:45.873Z","msg":"Using LegacyContextManager"}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:45.880Z","msg":"Adding destroy hook to clean up unresolved promises.","component":"async_hooks"}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:45.926Z","msg":"Agent state changed from stopped to starting."}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:45.957Z","msg":"Starting New Relic for Node.js connection process."}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:45.957Z","msg":"Agent state changed from starting to connecting."}
nodejs-terminator-1    | 127.0.0.1 - - [28/Jun/2023:11:03:46 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.74.0" "-"
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:47.156Z","msg":"Agent state changed from connecting to connected."}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:47.157Z","msg":"Connected to collector.eu01.nr-data.net:443 with agent run ID XXXXXXX.","component":"collector_api"}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:47.157Z","msg":"Reporting to: https://rpm.eu.newrelic.com/accounts/XXXXX/applications/XXXXXX","component":"collector_api"}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:47.158Z","msg":"Valid event_harvest_config received. Updating harvest cycles. {\"report_period_ms\":5000,\"harvest_limits\":{\"error_event_data\":8,\"log_event_data\":833,\"analytic_event_data\":833,\"custom_event_data\":250}}"}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:47.161Z","msg":"Agent state changed from connected to started."}
nodejs-nodejs-1        | {"v":0,"level":30,"name":"newrelic","hostname":"2242b93589b3","pid":20,"time":"2023-06-28T11:03:48.162Z","msg":"Starting initial 1000ms harvest."}
nodejs-nodejs-1        | /app/node_modules/newrelic/lib/transaction/tracer/index.js:211
nodejs-nodejs-1        |       throw err // Re-throwing application error, this is not an agent error.
nodejs-nodejs-1        |       ^
nodejs-nodejs-1        | 
nodejs-nodejs-1        | TypeError: Cannot redefine property: _body
nodejs-nodejs-1        |     at Function.defineProperty (<anonymous>)
nodejs-nodejs-1        |     at Application.wrapCreateContext (/app/node_modules/@newrelic/koa/lib/instrumentation.js:77:10)
nodejs-nodejs-1        |     at Object.applyTrap [as apply] (/app/node_modules/newrelic/lib/shim/shim.js:690:29)
nodejs-nodejs-1        |     at Server.handleRequest (/app/node_modules/koa/lib/application.js:155:24)
nodejs-nodejs-1        |     at Server.emit (node:events:390:28)
nodejs-nodejs-1        |     at LegacyContextManager.runInContext (/app/node_modules/newrelic/lib/context-manager/legacy-context-manager.js:59:23)
nodejs-nodejs-1        |     at Server.wrapped (/app/node_modules/newrelic/lib/transaction/tracer/index.js:203:37)
nodejs-nodejs-1        |     at Server.wrappedHandler (/app/node_modules/newrelic/lib/instrumentation/core/http.js:193:47)
nodejs-nodejs-1        |     at LegacyContextManager.runInContext (/app/node_modules/newrelic/lib/context-manager/legacy-context-manager.js:59:23)
nodejs-nodejs-1        |     at Server.wrapped (/app/node_modules/newrelic/lib/transaction/tracer/index.js:203:37)
nodejs-nodejs-1 exited with code 1

@koa/router and koa-router 8.03+ breaks segment naming for nested routes

Breaking change: koajs/router@fe8d745

Background:

When routes from one router are leveraged by another router, the "layers" that hold onto the middleware we've instrumented get updated with the additional outer route path via Layer.setPrefix(). Our instrumentation relies on lazy-reading the layer path so that the updated name is retrieved to name middleware segments.

With @koa/router^8.0.3 and koa-router^8.03, Layers are now cloned to allow for re-use / nesting in multiple routers. This change breaks our instrumentation because the original layer we have a handle on is not updated.

https://github.com/newrelic/node-newrelic-koa/blob/master/lib/router-instrumentation.js#L34

var router2 = new Router()
router2.get('/:second', function secondMiddleware(ctx) {
  ctx.body = ' second'
})
      
router.use('/:first', router2.routes())
app.use(router.routes())

For the code above, secondMiddleware would previously have a segment named: Nodejs/Middleware/Koa/secondMiddleware//:first/:second.

Segments are now missing the :first nested route prefix: Nodejs/Middleware/Koa/secondMiddleware//:second

Unfortunately, there doesn't seem to be any obvious quick-fix with the current way the instrumentation is setup.

[Repolinter] Open Source Policy Issues

Repolinter Report

🤖This issue was automatically generated by repolinter-action, developed by the Open Source and Developer Advocacy team at New Relic. This issue will be automatically updated or closed when changes are pushed. If you have any problems with this tool, please feel free to open a GitHub issue or give us a ping in #help-opensource.

This Repolinter run generated the following results:

❗ Error ❌ Fail ⚠️ Warn ✅ Pass Ignored Total
0 0 0 7 0 7

Passed #

Click to see rules

license-file-exists #

Found file (LICENSE). New Relic requires that all open source projects have an associated license contained within the project. This license must be permissive (e.g. non-viral or copyleft), and we recommend Apache 2.0 for most use cases. For more information please visit https://docs.google.com/document/d/1vML4aY_czsY0URu2yiP3xLAKYufNrKsc7o4kjuegpDw/edit.

readme-file-exists #

Found file (README.md). New Relic requires a README file in all projects. This README should give a general overview of the project, and should point to additional resources (security, contributing, etc.) where developers and users can learn further. For more information please visit https://github.com/newrelic/open-by-default.

readme-starts-with-community-plus-header #

The first 5 lines contain all of the requested patterns. (README.md). The README of a community plus project should have a community plus header at the start of the README. If you already have a community plus header and this rule is failing, your header may be out of date, and you should update your header with the suggested one below. For more information please visit https://opensource.newrelic.com/oss-category/.

readme-contains-link-to-security-policy #

Contains a link to the security policy for this repository (README.md). New Relic recommends putting a link to the open source security policy for your project (https://github.com/newrelic/<repo-name>/security/policy or ../../security/policy) in the README. For an example of this, please see the "a note about vulnerabilities" section of the Open By Default repository. For more information please visit https://nerdlife.datanerd.us/new-relic/security-guidelines-for-publishing-source-code.

readme-contains-discuss-topic #

Contains a link to the appropriate discuss.newrelic.com topic (README.md). New Relic recommends directly linking the your appropriate discuss.newrelic.com topic in the README, allowing developer an alternate method of getting support. For more information please visit https://nerdlife.datanerd.us/new-relic/security-guidelines-for-publishing-source-code.

code-of-conduct-should-not-exist-here #

New Relic has moved the CODE_OF_CONDUCT file to a centralized location where it is referenced automatically by every repository in the New Relic organization. Because of this change, any other CODE_OF_CONDUCT file in a repository is now redundant and should be removed. Note that you will need to adjust any links to the local CODE_OF_CONDUCT file in your documentation to point to the central file (README and CONTRIBUTING will probably have links that need updating). For more information please visit https://docs.google.com/document/d/1y644Pwi82kasNP5VPVjDV8rsmkBKclQVHFkz8pwRUtE/view. Did not find a file matching the specified patterns. All files passed this test.

third-party-notices-file-exists #

Found file (THIRD_PARTY_NOTICES_FOOTER.md). A THIRD_PARTY_NOTICES.md file can be present in your repository to grant attribution to all dependencies being used by this project. This document is necessary if you are using third-party source code in your project, with the exception of code referenced outside the project's compiled/bundled binary (ex. some Java projects require modules to be pre-installed in the classpath, outside the project binary and therefore outside the scope of the THIRD_PARTY_NOTICES). Please review your project's dependencies and create a THIRD_PARTY_NOTICES.md file if necessary. For JavaScript projects, you can generate this file using the oss-cli. For more information please visit https://docs.google.com/document/d/1y644Pwi82kasNP5VPVjDV8rsmkBKclQVHFkz8pwRUtE/view.

Cannot redefine property: _body

Description

Getting an error when the server attempts to process any API requests

Expected Behavior

Server to start and be able to process requests. I have downgraded to "newrelic": "^9.15.0", and it goes back to working

Steps to Reproduce

Starting a Koa server with New Relic & Koa plugin

Your Environment

  • Node: v16.20.1
  • "koa": "^2.14.2",
  • "koa-body": "^6.0.1",
  • "koa-cognito-middleware": "^1.4.7",
  • "koa-easy-ws": "^2.1.0",
  • "koa-helmet": "^7.0.2",
  • "koa-router": "^12.0.0",
  • "koa-static": "^5.0.0",
  • "@newrelic/koa": "^7.2.0",
  • "newrelic": "^10.6.2",

Additional context

/Users/robin/Projects/Simple-Api/node_modules/@newrelic/koa/lib/instrumentation.js:77
Object.defineProperty(context.response, '_body', {
^
TypeError: Cannot redefine property: _body
at Function.defineProperty ()
at Application.wrapCreateContext (/Users/robin/ProjectsSimple-Api/node_modules/@newrelic/koa/lib/instrumentation.js:77:10)
at Object.applyTrap [as apply] (/Users/robin/Projects/Simple-Api//node_modules/newrelic/lib/shim/shim.js:691:29)
at Server.handleRequest (/Users/robin/Projects/Simple-Api//node_modules/koa/lib/application.js:155:24)
at Server.emit (node:events:513:28)
at Server.emit (node:domain:489:12)
at LegacyContextManager.runInContext (/Users/robin/Projects/Simple-Api/node_modules/newrelic/lib/context-manager/legacy-context-manager.js:59:23)
at Server.wrapped (/Users/robin/Projects/Simple-Api//node_modules/newrelic/lib/transaction/tracer/index.js:203:37)
at Server.wrappedHandler (/Users/robin/Projects/Simple-Api//node_modules/newrelic/lib/instrumentation/core/http.js:193:47)
at LegacyContextManager.runInContext (/Users/robin/Projects/Simple-Api//node_modules/newrelic/lib/context-manager/legacy-context-manager.js:59:23)
at Server.wrapped (/Users/robin/Projects/Simple-Api//node_modules/newrelic/lib/transaction/tracer/index.js:203:37)
at Server.wrapTransactionInvocation (/Users/robin/Projects/Simple-Api//node_modules/newrelic/lib/transaction/tracer/index.js:123:71)
at Server.wrappedEmit [as emit] (/Users/robin/Projects/Simple-Api//node_modules/newrelic/lib/instrumentation/core/http.js:443:28)
at parserOnIncoming (node:_http_server:998:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)

Convert CI to GitHub Actions

  • Users can run unit tests at a minimum.

Would aim for all tests functioning for external PR's (forked repos) with these efforts.

Koa instrumentation does not work with the New Relic ESM module loader

Description

When attempting to load the New Relic Agent (v9.7.3) using the ESM module loader described here, the automatic instrumentation for Koa fails with the following error:

{"v":0,"level":40,"name":"newrelic","hostname":"0bfcea2519cb","pid":82743,"time":"2022-12-14T21:10:08.234Z","msg":"Custom instrumentation for koa failed. Please report this to the maintainers of the custom instrumentation.","component":"shimmer","stack":"TypeError: Cannot convert undefined or null to object\n at Function.keys (<anonymous>)\n at Object.initialize [as onRequire] (/my-system/node_modules/@newrelic/koa/lib/instrumentation.js:10:31)\n at instrumentPostLoad (/my-system/node_modules/newrelic/lib/shimmer.js:534:25)\n at _postLoad (/my-system/node_modules/newrelic/lib/shimmer.js:591:12)\n at Object.instrumentPostLoad (/my-system/node_modules/newrelic/lib/shimmer.js:477:20)\n at wrapModule (file:///my-system/node_modules/newrelic/lib/esm-shim.mjs:35:18)\n at file:///my-system/node_modules/koa/dist/koa.mjs?hasNrInstrumentation=true:4:28\n at ModuleJob.run (node:internal/modules/esm/module_job:193:25)\n at async Promise.all (index 0)\n at async ESMLoader.import (node:internal/modules/esm/loader:526:24)","message":"Cannot convert undefined or null to object"}

The root cause is at line 10 of instrumentation.js
if (!shim || !Koa || Object.keys(Koa.prototype).length > 1) {

When loaded via the ESM module loader, `Koa.prototype' is undefined.

I was able to fix it by simply adding the following line before the if statement above:
Koa.prototype = Koa.default.prototype;

The 'Koa.default' export was added for this purpose in the Koa project. See:

Steps to Reproduce

Run the New Relic agent in a Koa project following the instructions for using the ESM module loader, and look at the agent logs to find the error above.

koa instrumentation crashes when running on koa-router > 8.0.2

Description

We pinned versioned tests for koa-router and @koa/router to <=8.0.2 in this commit. I don't see any follow up work to address but I notice the instrumentation crashes with:

TypeError: Cannot redefine property: _body
    at Function.defineProperty (<anonymous>)
    at Application.wrapCreateContext (/Users/revans/code/node-newrelic-koa/lib/instrumentation.js:77:10)
    at Object.applyTrap [as apply] (/Users/revans/code/release/node-newrelic/lib/shim/shim.js:690:29)
    at Server.handleRequest (/Users/revans/code/NodeTestBenches/koa/node_modules/koa/lib/application.js:147:24)
    at Server.emit (node:events:513:28)
    at LegacyContextManager.runInContext (/Users/revans/code/release/node-newrelic/lib/context-manager/legacy-context-manager.js:59:23)
    at Server.wrapped (/Users/revans/code/release/node-newrelic/lib/transaction/tracer/index.js:203:37)
    at Server.wrappedHandler (/Users/revans/code/release/node-newrelic/lib/instrumentation/core/http.js:193:47)
    at LegacyContextManager.runInContext (/Users/revans/code/release/node-newrelic/lib/context-manager/legacy-context-manager.js:59:23)
    at Server.wrapped (/Users/revans/code/release/node-newrelic/lib/transaction/tracer/index.js:203:37)
    at Server.wrapTransactionInvocation (/Users/revans/code/release/node-newrelic/lib/transaction/tracer/index.js:123:71)
    at Server.wrappedEmit [as emit] (/Users/revans/code/release/node-newrelic/lib/instrumentation/core/http.js:443:28)
    at parserOnIncoming (node:_http_server:1091:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17)

Expected Behavior

Instrumentation functions regardless of koa router version.

Steps to Reproduce

  • Create a koa app that has a @koa/router > 8.0.2
  • Navigate to application.

[Repolinter] Open Source Policy Issues

Repolinter Report

🤖This issue was automatically generated by repolinter-action, developed by the Open Source and Developer Advocacy team at New Relic. This issue will be automatically updated or closed when changes are pushed. If you have any problems with this tool, please feel free to open a GitHub issue or give us a ping in #help-opensource.

This Repolinter run generated the following results:

❗ Error ❌ Fail ⚠️ Warn ✅ Pass Ignored Total
0 1 0 5 0 6

Fail #

readme-starts-with-community-plus-header #

The README of a community plus project should have a community plus header at the start of the README. If you already have a community plus header and this rule is failing, your header may be out of date. For more information please visit https://opensource.newrelic.com/oss-category/. Below is a list of files or patterns that failed:

  • README.md: The first 1 lines do not contain the pattern(s): Open source Community Plus header (see https://opensource.newrelic.com/oss-category).
    • 🔨 Suggested Fix: prepend [![Community Plus header](https://github.com/newrelic/opensource-website/raw/master/src/images/categories/Community_Plus.png)](https://opensource.newrelic.com/oss-category/#community-plus) to file

Passed #

Click to see rules

license-file-exists #

Found file (LICENSE). New Relic requires that all open source projects have an associated license contained within the project. This license must be permissive (e.g. non-viral or copyleft), and we recommend Apache 2.0 for most use cases. For more information please visit https://docs.google.com/document/d/1vML4aY_czsY0URu2yiP3xLAKYufNrKsc7o4kjuegpDw/edit.

readme-file-exists #

Found file (README.md). New Relic requires a README file in all projects. This README should give a general overview of the project, and should point to additional resources (security, contributing, etc.) where developers and users can learn further. For more information please visit https://github.com/newrelic/open-by-default.

readme-contains-link-to-security-policy #

Contains a link to the security policy for this repository (README.md). New Relic recommends putting a link to the open source security policy for your project (https://github.com/newrelic/<repo-name>/security/policy or ../../security/policy) in the README. For an example of this, please see the "a note about vulnerabilities" section of the Open By Default repository. For more information please visit https://nerdlife.datanerd.us/new-relic/security-guidelines-for-publishing-source-code.

readme-contains-discuss-topic #

Contains a link to the appropriate discuss.newrelic.com topic (README.md). New Relic recommends directly linking the your appropriate discuss.newrelic.com topic in the README, allowing developer an alternate method of getting support. For more information please visit https://nerdlife.datanerd.us/new-relic/security-guidelines-for-publishing-source-code.

third-party-notices-file-exists #

Found file (THIRD_PARTY_NOTICES.md). A THIRD_PARTY_NOTICES.md file can be present in your repository to grant attribution to all dependencies being used by this project. This document is necessary if you are using third-party source code in your project, with the exception of code referenced outside the project's compiled/bundled binary (ex. some Java projects require modules to be pre-installed in the classpath, outside the project binary and therefore outside the scope of the THIRD_PARTY_NOTICES). Please review your project's dependencies and create a THIRD_PARTY_NOTICES.md file if necessary. For JavaScript projects, you can generate this file using the oss-cli. For more information please visit https://docs.google.com/document/d/1y644Pwi82kasNP5VPVjDV8rsmkBKclQVHFkz8pwRUtE/view.

Minimal code cleanup

We are already in decent shape but do a pass for general things outlined in the Engineering Plan.

Regex @nijotz used on the last story:

rg --pcre2 '(?<!SELECT)(// |^ *\*(?!/))(?! Copyright|.*Apache|.*eslint)'

Update prep-release workflow

This repo is using the old way of prepping a release that requires updating the release notes. See example here: cc838c6

Need to update the prep release workflow to use the correct workflow like we do in the node agent repo.

Sample PR

Update Pull Requests settings in Settings > General to squash merges, use PR title and delete head branches

screenshot 2024-03-20 at 9 19 13 AM

Missing or ended transaction can result in error

The _matchedRoute code may throw if there's no active transaction found. We need to account for situations where something else may have gone wrong, impacting state loss or transaction ending sooner than expected, so we do not end up throwing an uncaught error.

https://github.com/newrelic/node-newrelic-koa/blob/master/lib/instrumentation.js#L88

This code needs to check that the transaction is not null.

        const tx = shim.agent.tracer.getTransaction()

        if (context.__NR_matchedRoute) {
          tx.nameState.popPath()
        }

        tx.nameState.appendPath(match.path)
        tx.nameState.markPath()

Would double-check other parts of the code-base, in case we have other exposure.

This was initially discovered as a part of: #32

koa: add node 20

Is your feature request related to a problem? Please describe.

  • Add Node 20 to CI and drop Node 14

Switch to 'main' as default branch

We've settled on main as the new default branch name.

This will involve creating and migrating to the new branch before deleting the prior. We'll also want to ensure we change the base of any existing PR's etc.

Hanselman has some helpful instructions on the blog: https://www.hanselman.com/blog/EasilyRenameYourGitDefaultBranchFromMasterToMain.aspx. I'm sure there are other useful resources out there as well.

  • Change default branch in repo settings
  • Change the base of all open PRs
  • Copy master branch protection rules to main
  • Edit any release documents to reference main instead of master
  • Setup Snyk to use main

Readme Updates

Summary

  • Should conform to new open source template.
    • See the internal repo template project.
  • Clear instructions for development and "building".
  • For Explorer's Hub... perhaps we just want to point to the main agent topic? This is the link to the main agent area: https://discuss.newrelic.com/c/support-products-agents/node-js-agent/
  • Update any out of date information

Depending on the amount of content, may want to run by the docs team. They had a bit of consistency and branding changes to the main agent readme.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.