Skip to content

Commit

Permalink
simplify baggage code and add test case (#4858)
Browse files Browse the repository at this point in the history
  • Loading branch information
ida613 authored Nov 6, 2024
1 parent 0b4dab7 commit 8112f6c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 18 deletions.
25 changes: 9 additions & 16 deletions packages/dd-trace/src/opentracing/propagation/text_map.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,26 +123,19 @@ class TextMapPropagator {
})
}
if (this._hasPropagationStyle('inject', 'baggage')) {
if (this._config.baggageMaxItems < 1) return
let baggage = ''
let counter = 1
let itemCounter = 0
let byteCounter = 0

for (const [key, value] of Object.entries(spanContext._baggageItems)) {
baggage += `${this._encodeOtelBaggageKey(String(key).trim())}=${encodeURIComponent(String(value).trim())},`
if (counter === this._config.baggageMaxItems || counter > this._config.baggageMaxItems) break
counter += 1
const item = `${this._encodeOtelBaggageKey(String(key).trim())}=${encodeURIComponent(String(value).trim())},`
itemCounter += 1
byteCounter += item.length
if (itemCounter > this._config.baggageMaxItems || byteCounter > this._config.baggageMaxBytes) break
baggage += item
}

baggage = baggage.slice(0, baggage.length - 1)
let buf = Buffer.from(baggage)
if (buf.length > this._config.baggageMaxBytes) {
const originalBaggages = baggage.split(',')
buf = buf.subarray(0, this._config.baggageMaxBytes)
const truncatedBaggages = buf.toString('utf8').split(',')
const lastPairIndex = truncatedBaggages.length - 1
if (truncatedBaggages[lastPairIndex] !== originalBaggages[lastPairIndex]) {
truncatedBaggages.splice(lastPairIndex, 1)
}
baggage = truncatedBaggages.slice(0, this._config.baggageMaxItems).join(',')
}
if (baggage) carrier.baggage = baggage
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,13 @@ describe('TextMapPropagator', () => {
it('should handle special characters in baggage', () => {
const carrier = {}
const baggageItems = {
'",;\\()/:<=>?@[]{}': '",;\\'
'",;\\()/:<=>?@[]{}🐶é我': '",;\\🐶é我'
}
const spanContext = createContext({ baggageItems })

propagator.inject(spanContext, carrier)
expect(carrier.baggage).to.be.equal('%22%2C%3B%5C%28%29%2F%3A%3C%3D%3E%3F%40%5B%5D%7B%7D=%22%2C%3B%5C')
// eslint-disable-next-line max-len
expect(carrier.baggage).to.be.equal('%22%2C%3B%5C%28%29%2F%3A%3C%3D%3E%3F%40%5B%5D%7B%7D%F0%9F%90%B6%C3%A9%E6%88%91=%22%2C%3B%5C%F0%9F%90%B6%C3%A9%E6%88%91')
})

it('should drop excess baggage items when there are too many pairs', () => {
Expand Down

0 comments on commit 8112f6c

Please sign in to comment.