Skip to content

Commit

Permalink
add namespace support for async storage
Browse files Browse the repository at this point in the history
  • Loading branch information
rochdev committed Oct 11, 2024
1 parent 6052944 commit 5b87174
Show file tree
Hide file tree
Showing 3 changed files with 71 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 }
20 changes: 20 additions & 0 deletions packages/datadog-core/src/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'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.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 5b87174

Please sign in to comment.