Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add namespace support for async storage #4775

Merged
merged 2 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions packages/datadog-core/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
'use strict'

const { AsyncLocalStorage } = require('async_hooks')

const storage = new AsyncLocalStorage()
const storage = require('./src/storage')

module.exports = { storage }
21 changes: 21 additions & 0 deletions packages/datadog-core/src/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict'

const { AsyncLocalStorage } = require('async_hooks')

const storages = Object.create(null)
const legacyStorage = new AsyncLocalStorage()

const storage = function (namespace) {
if (!storages[namespace]) {
storages[namespace] = new AsyncLocalStorage()
}
return storages[namespace]
}

storage.disable = legacyStorage.disable.bind(legacyStorage)
storage.enterWith = legacyStorage.enterWith.bind(legacyStorage)
storage.exit = legacyStorage.exit.bind(legacyStorage)
storage.getStore = legacyStorage.getStore.bind(legacyStorage)
storage.run = legacyStorage.run.bind(legacyStorage)

module.exports = storage
50 changes: 50 additions & 0 deletions packages/datadog-core/test/storage.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict'

require('../../dd-trace/test/setup/tap')

const { expect } = require('chai')
const storage = require('../src/storage')

describe('storage', () => {
let testStorage
let testStorage2

beforeEach(() => {
testStorage = storage('test')
testStorage2 = storage('test2')
})

afterEach(() => {
testStorage.enterWith(undefined)
testStorage2.enterWith(undefined)
})

it('should enter a store', done => {
const store = 'foo'

testStorage.enterWith(store)

setImmediate(() => {
expect(testStorage.getStore()).to.equal(store)
done()
})
})

it('should enter stores by namespace', done => {
const store = 'foo'
const store2 = 'bar'

testStorage.enterWith(store)
testStorage2.enterWith(store2)

setImmediate(() => {
expect(testStorage.getStore()).to.equal(store)
expect(testStorage2.getStore()).to.equal(store2)
done()
})
})

it('should return the same storage for a namespace', () => {
expect(storage('test')).to.equal(testStorage)
})
})
Loading