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

refactor!: specification compliant baggage #1876

Merged
merged 11 commits into from
Feb 5, 2021
43 changes: 35 additions & 8 deletions packages/opentelemetry-api/src/baggage/Baggage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,43 @@
* limitations under the License.
*/

import { EntryValue } from './EntryValue';
import { BaggageEntry, BaggageEntryMetadata } from './Entry';

/**
* Baggage represents collection of entries. Each key of
* Baggage is associated with exactly one value. Baggage
* is serializable, to facilitate propagating it not only inside the process
* but also across process boundaries. Baggage is used to annotate
* telemetry with the name:value pair Entry. Those values can be used to add
* dimension to the metric or additional contest properties to logs and traces.
* Baggage represents collection of key-value pairs with optional metadata.
* Each key of Baggage is associated with exactly one value.
* Baggage may be used to annotate and enrich telemetry data.
*/
export interface Baggage {
[entryKey: string]: EntryValue;
/**
* Get an entry from Baggage if it exists
*
* @param key The key which identifies the BaggageEntry
*/
getEntry(key: string): BaggageEntry | undefined;

/**
* Get a list of all entries in the Baggage
*/
getAllEntries(): BaggageEntry[];

/**
* Create a new Baggage from this baggage with a new entry.
*
* @param key string which identifies the baggage entry
* @param value string value of the baggage
* @param metadata optional entry metadata
*/
setEntry(
Flarna marked this conversation as resolved.
Show resolved Hide resolved
key: string,
value: string,
metadata?: BaggageEntryMetadata
): Baggage;

/**
* Create a new baggage containing all entries from this except the removed entry
dyladan marked this conversation as resolved.
Show resolved Hide resolved
*
* @param key key identifying the entry to be removed
*/
removeEntry(key: string): Baggage;
dyladan marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface EntryValue {
/** `String` value of the `EntryValue`. */

export interface BaggageEntry {
/** `String` key of the `BaggageEntry` */
key: string;

/** `String` value of the `BaggageEntry`. */
value: string;
/**
* ttl is an integer that represents number of hops an entry can
* propagate.
* Metadata is an optional string property defined by the W3C baggage specification.
* It currently has no special meaning defined by the specification.
*/
ttl?: EntryTtl;
metadata?: BaggageEntryMetadata;
}

/**
* EntryTtl is an integer that represents number of hops an entry can propagate.
*
* For now, ONLY special values (0 and -1) are supported.
* Serializable Metadata defined by the W3C baggage specification.
* It currently has no special meaning defined by the OpenTelemetry or W3C.
*/
export enum EntryTtl {
/**
* NO_PROPAGATION is considered to have local context and is used within the
* process it created.
*/
NO_PROPAGATION = 0,

/** UNLIMITED_PROPAGATION can propagate unlimited hops. */
UNLIMITED_PROPAGATION = -1,
export interface BaggageEntryMetadata {
toString(): string;
}
47 changes: 47 additions & 0 deletions packages/opentelemetry-api/src/baggage/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { Baggage } from './Baggage';
import { BaggageEntry, BaggageEntryMetadata } from './Entry';
import { BaggageImpl } from './internal/baggage';

export * from './Baggage';
export * from './Entry';

/**
* Create a new Baggage with optional entries
*
* @param entries An array of baggage entries the new baggage should contain
*/
export function createBaggage(entries: BaggageEntry[] = []): Baggage {
return new BaggageImpl(entries);
}

/**
* Create a serializable BaggageEntryMetadata object from a string.
*
* @param str string metadata. Format is currently not defined by the spec and has no special meaning.
*
*/
export function baggageEntryMetadataFromString(
str: string
): BaggageEntryMetadata {
return {
toString: function () {
return str;
},
};
}
47 changes: 47 additions & 0 deletions packages/opentelemetry-api/src/baggage/internal/baggage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { Baggage } from '../Baggage';
import type { BaggageEntry } from '../Entry';

export class BaggageImpl implements Baggage {
constructor(private _entries: BaggageEntry[]) {}
Flarna marked this conversation as resolved.
Show resolved Hide resolved

getEntry(key: string): BaggageEntry | undefined {
const entry = this._entries.find(e => e.key === key);
if (!entry) {
return undefined;
}

return Object.assign(Object.create(null), entry);
}

getAllEntries(): BaggageEntry[] {
return this._entries.map(e => Object.assign(Object.create(null), e));
}

setEntry(key: string, value: string, metadata?: string): BaggageImpl {
const newBaggage = this.removeEntry(key);
newBaggage._entries.push(
Object.assign(Object.create(null), { key, value, metadata })
);
return newBaggage;
}

removeEntry(key: string): BaggageImpl {
return new BaggageImpl(this._entries.filter(e => e.key !== key));
}
}
3 changes: 1 addition & 2 deletions packages/opentelemetry-api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ export * from './common/Time';
export * from './context/context';
export * from './context/propagation/TextMapPropagator';
export * from './context/propagation/NoopTextMapPropagator';
export * from './baggage/Baggage';
export * from './baggage/EntryValue';
export * from './baggage';
export * from './trace/attributes';
export * from './trace/Event';
export * from './trace/link_context';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@
import {
Baggage,
Context,
BaggageEntry,
getBaggage,
setBaggage,
TextMapGetter,
TextMapPropagator,
TextMapSetter,
createBaggage,
baggageEntryMetadataFromString,
} from '@opentelemetry/api';

const KEY_PAIR_SEPARATOR = '=';
Expand All @@ -36,10 +39,6 @@ export const MAX_NAME_VALUE_PAIRS = 180;
export const MAX_PER_NAME_VALUE_PAIRS = 4096;
// Maximum total length of all name-value pairs allowed by w3c spec
export const MAX_TOTAL_LENGTH = 8192;
type KeyPair = {
key: string;
value: string;
};

/**
* Propagates {@link Baggage} through Context format propagation.
Expand Down Expand Up @@ -70,46 +69,50 @@ export class HttpBaggage implements TextMapPropagator {
}

private _getKeyPairs(baggage: Baggage): string[] {
return Object.keys(baggage).map(
(key: string) =>
`${encodeURIComponent(key)}=${encodeURIComponent(baggage[key].value)}`
);
return baggage
.getAllEntries()
.map(
entry =>
`${encodeURIComponent(entry.key)}=${encodeURIComponent(entry.value)}`
);
}

extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {
const headerValue: string = getter.get(carrier, BAGGAGE_HEADER) as string;
if (!headerValue) return context;
const baggage: Baggage = {};
const entries: BaggageEntry[] = [];
if (headerValue.length == 0) {
return context;
}
const pairs = headerValue.split(ITEMS_SEPARATOR);
pairs.forEach(entry => {
const keyPair = this._parsePairKeyValue(entry);
if (keyPair) {
baggage[keyPair.key] = { value: keyPair.value };
const parsedEntry = this._parsePairKeyValue(entry);
if (parsedEntry) {
entries.push(parsedEntry);
}
});
if (Object.entries(baggage).length === 0) {
if (entries.length === 0) {
return context;
}
return setBaggage(context, baggage);
return setBaggage(context, createBaggage(entries));
}

private _parsePairKeyValue(entry: string): KeyPair | undefined {
private _parsePairKeyValue(entry: string): BaggageEntry | undefined {
const valueProps = entry.split(PROPERTIES_SEPARATOR);
if (valueProps.length <= 0) return;
const keyPairPart = valueProps.shift();
if (!keyPairPart) return;
const keyPair = keyPairPart.split(KEY_PAIR_SEPARATOR);
if (keyPair.length != 2) return;
const key = decodeURIComponent(keyPair[0].trim());
let value = decodeURIComponent(keyPair[1].trim());
const value = decodeURIComponent(keyPair[1].trim());
let metadata;
if (valueProps.length > 0) {
value =
value + PROPERTIES_SEPARATOR + valueProps.join(PROPERTIES_SEPARATOR);
metadata = baggageEntryMetadataFromString(
valueProps.join(PROPERTIES_SEPARATOR)
);
}
return { key, value };
return { key, value, metadata };
}

fields(): string[] {
Expand Down
Loading