Skip to content

Commit

Permalink
add namespace support for async storage (#4775)
Browse files Browse the repository at this point in the history
  • Loading branch information
rochdev authored Nov 13, 2024
1 parent 1ce47d2 commit 83e11a3
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 3 deletions.
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)
})
})

0 comments on commit 83e11a3

Please sign in to comment.