diff --git a/CHANGELOG.md b/CHANGELOG.md index d605eff3e1..ab76cfe617 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ For experimental package changes, see the [experimental CHANGELOG](experimental/ ### :rocket: (Enhancement) +* feat(api): add `getActiveBaggage` API [#3385](https://github.com/open-telemetry/opentelemetry-js/pull/3385) + ### :bug: (Bug Fix) * fix(sdk-metrics): use default Resource to comply with semantic conventions [#3411](https://github.com/open-telemetry/opentelemetry-js/pull/3411) @pichlermarc diff --git a/api/src/api/propagation.ts b/api/src/api/propagation.ts index 2cd9aec760..24c9c1f73f 100644 --- a/api/src/api/propagation.ts +++ b/api/src/api/propagation.ts @@ -30,6 +30,7 @@ import { } from '../propagation/TextMapPropagator'; import { getBaggage, + getActiveBaggage, setBaggage, deleteBaggage, } from '../baggage/context-helpers'; @@ -112,6 +113,8 @@ export class PropagationAPI { public getBaggage = getBaggage; + public getActiveBaggage = getActiveBaggage; + public setBaggage = setBaggage; public deleteBaggage = deleteBaggage; diff --git a/api/src/baggage/context-helpers.ts b/api/src/baggage/context-helpers.ts index ae7b4a78e0..93a5ffca83 100644 --- a/api/src/baggage/context-helpers.ts +++ b/api/src/baggage/context-helpers.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +import { ContextAPI } from '../api/context'; import { createContextKey } from '../context/context'; import { Context } from '../context/types'; import { Baggage } from './types'; @@ -33,6 +34,15 @@ export function getBaggage(context: Context): Baggage | undefined { return (context.getValue(BAGGAGE_KEY) as Baggage) || undefined; } +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +export function getActiveBaggage(): Baggage | undefined { + return getBaggage(ContextAPI.getInstance().active()); +} + /** * Store a baggage in the given context * diff --git a/api/test/common/baggage/Baggage.test.ts b/api/test/common/baggage/Baggage.test.ts index 81895306c0..28401c0524 100644 --- a/api/test/common/baggage/Baggage.test.ts +++ b/api/test/common/baggage/Baggage.test.ts @@ -16,6 +16,7 @@ import * as assert from 'assert'; import { + context, ROOT_CONTEXT, propagation, baggageEntryMetadataFromString, @@ -131,6 +132,20 @@ describe('Baggage', () => { assert.strictEqual(bag, propagation.getBaggage(ctx)); }); + + it('should get the current baggage', () => { + const entries = { + 'banana': {value: 'boats'} + }; + const bag = propagation.createBaggage(entries); + const ctx = propagation.setBaggage(ROOT_CONTEXT, bag); + + context.setGlobalContextManager({ active: () => ctx, disable: () => {} } as any); + + assert.strictEqual(bag, propagation.getActiveBaggage()); + + context.disable(); + }); }); describe('metadata', () => {