Skip to content

Ability for async functions to retreive their CLS context #32062

@gireeshpunathil

Description

@gireeshpunathil

Is your feature request related to a problem? Please describe.
Please describe the problem you are trying to solve.

Right now, the AsyncLocalStorage object needs to be externally available for the async functions to avail the store.

Describe the solution you'd like
Please describe the desired behavior.

Implement a getContextCLS API that returns the AsyncLocalStorage object under which this asynchronous call was initiated. Return undefined, if it was not run under AsyncLocalStorage semantics.

Illustration:

const { AsyncLocalStorage } = require('async_hooks');

function main() {
  const cls1 = new AsyncLocalStorage();
  const cls2 = new AsyncLocalStorage();
  cls1.run(() => {
    const store = cls1.getStore()
    store.set('x', 'y')
    setTimeout(foo, 1000)
  })
  
  cls2.run(() => {
    const store = cls2.getStore()
    store.set('x', 'z')
    setTimeout(foo, 1000)
  })
}


function foo() {
  // obtain the cls object here that this async call was part of
  // for example:
  // const cls = getContextCLS()
  //  const store = cls.getStore()
  //  console.log(store.get('x')
  // prints 'y' and 'z' as and when those are called.
}

main()

Use case: in a concurrent workload scenario, it is not easy to maintain AsyncLocalStorage objects globally, and across multiple async function families.

Describe alternatives you've considered
Please describe alternative solutions or features you have considered.

Alternative is to share these objects globally (which is not very attractive)

Metadata

Metadata

Assignees

No one assigned

    Labels

    async_hooksIssues and PRs related to the async hooks subsystem.feature requestIssues that request new features to be added to Node.js.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions