tctx
Version:
W3C Trace Contexts made simple
76 lines (74 loc) • 2.53 kB
text/typescript
/**
* A simple implementation of the {@link https://www.w3.org/TR/trace-context-2/|W3C Trace Context specification level 2}.
*
* This module provides a simple API for creating, parsing, and manipulating tracestate headers. You will probably also
* be relying on the {@link {import('./traceparent.ts')}} module to create and parse traceparent headers.
*
* Tracestates are effectivly a ring buffer of 32 key-value pairs, where the key is a string of up to 256 characters and
* the value is a string of up to 256 characters. The key must be unique within the tracestate.
*
* Updateing the tracestate is done by calling the {@link {Tracestate.set}} method, which will update the value of the
* key if it exists (and move it to the front), or prepend a new key-value pair to the front of the tracestate. If the
* tracestate is full, the oldest key-value pair will be removed.
*
* @example
* ```ts
* import * as tp from './traceparent.ts';
* import * as ts = from './tracestate.ts';
*
* let traceparent, tracestate, tmp;
* tmp = req.headers.get('traceparent');
* if (tmp) traceparent = ts.parse(tmp);
* tmp = req.headers.get('tracestate');
* // only parse the tracestate, if we have a valid parsed traceparent, as per spec
* if (traceparent && tmp) tracestate = ts.parse(tmp);
* traceparent ||= tp.make();
*
* let headers = new Headers();
* if (tracestate) headers.set('tracestate', String(tracestate));
*
* tracestate.set('vendor', 'value');
*
* fetch('/downstream', {
* headers: { traceparent: traceparent.child(), tracestate }
* })
* ```
*
* @module
*/
/**
* The Tracestate type represents a W3C Trace Context tracestate header, implemented as a ring buffer using a javascript {@link Map}.
*/
declare class Tracestate extends Map {
set(key: string, value: unknown): this;
toString(): string;
}
/**
* Create a new tracestate instance.
*
* @example
* ```ts
* let tracestate = make({ key: 'value' });
* tracestate.set('key2', 'value2');
*
* console.log(String(tracestate)); // 'key2=value2,key=value'
* ```
*/
export declare function make(initial?: Iterable<[string, unknown]> | undefined): Tracestate;
/**
* Parse a tracestate header string into a tracestate instance.
*
* @example
* ```ts
* let tracestate = parse('key=value,key2=value2');
*
* console.log(tracestate.get('key')); // 'value'
* console.log(tracestate.get('key2')); // 'value2'
*
* tracestate.set('key', 'new-value');
*
* console.log(String(tracestate)); // 'key=new-value,key2=value2'
* ```
*/
export declare function parse(value: string): Tracestate;
export {};