Skip to content

fetch: design of wrapper makes instrumenting miss the first request #43915

@bizob2828

Description

@bizob2828

What is the problem this feature will solve?

fetch shipped in 18.x which is a wrapper around undici. I work on the New Relic Node.js agent and we noticed an issue where we weren't properly propagating state through a fetch command. When I tried registering our undici instrumentation, I noticed the first request is missed.

This is due to the lazy loading of the internal undici. Also since this is an internal module load I couldn't rely on our CJS instrumentation to key off of a require of a file path.

const diagnostics = require('diagnostics_channel')
const originalFetch = global.fetch

global.fetch = function wrappedFetch() {
  const fetchRequest = originalFetch.apply(this, arguments)
  // add your code now that undici has been loaded and can subscribe to the undici:* events.  
  diagnosticsChannel.channel('undici:request:create').subscribe(({ request }) => {
    // do stuff with the undici request
  })
  return fetchRequest
}

What is the feature you are proposing to solve the problem?

Change how undici is getting loaded as an internal to make it possible to properly register channels before the first fetch is ever called. Also as aside, I may be wrong but making fetch async is creating an unnecessary promise right?

  async function fetch(input, init = undefined) {
    emitExperimentalWarning('The Fetch API');
    return lazyUndici().fetch(input, init);
  }

What alternatives have you considered?

The above code snippet feels like the only option which will miss the first request as the subscriptions are not present. I guess an alternative would be users to preemptively subscribe to channels but I get how that could be problematic and lead to hijacking of name spaces.

Metadata

Metadata

Assignees

No one assigned

    Labels

    diagnostics_channelIssues and PRs related to diagnostics channelfeature requestIssues that request new features to be added to Node.js.fetchIssues and PRs related to the Fetch API

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions