/** * @since 1.0.0 */ interface Context { /** * Get a value from the context. * * @param key key which identifies a context value */ getValue(key: symbol): unknown; /** * Create a new context which inherits from this context and has * the given key set to the given value. * * @param key context key for which to set the value * @param value value to set for the given key */ setValue(key: symbol, value: unknown): Context; /** * Return a new context which inherits from this context but does * not contain a value for the given key. * * @param key context key for which to clear a value */ deleteValue(key: symbol): Context; } /** * Attributes is a map from string to attribute values. * * Note: only the own enumerable keys are counted as valid attribute keys. * * @since 1.3.0 */ interface Attributes { [attributeKey: string]: AttributeValue | undefined; } /** * Attribute values may be any non-nullish primitive value except an object. * * null or undefined attribute values are invalid and will result in undefined behavior. * * @since 1.3.0 */ type AttributeValue = string | number | boolean | Array | Array | Array; interface ExceptionWithCode { code: string | number; name?: string; message?: string; stack?: string; } interface ExceptionWithMessage { code?: string | number; message: string; name?: string; stack?: string; } interface ExceptionWithName { code?: string | number; message?: string; name: string; stack?: string; } /** * Defines Exception. * * string or an object with one of (message or name or code) and optional stack * * @since 1.0.0 */ type Exception = ExceptionWithCode | ExceptionWithMessage | ExceptionWithName | string; /** * Defines High-Resolution Time. * * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970. * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds. * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150. * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds: * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210. * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds: * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000. * This is represented in HrTime format as [1609504210, 150000000]. * * @since 1.0.0 */ type HrTime = [number, number]; /** * Defines TimeInput. * * hrtime, epoch milliseconds, performance.now() or Date * * @since 1.0.0 */ type TimeInput = HrTime | number | Date; /** * @deprecated please use {@link Attributes} * @since 1.0.0 */ type SpanAttributes = Attributes; /** * @deprecated please use {@link AttributeValue} * @since 1.0.0 */ type SpanAttributeValue = AttributeValue; /** * @since 1.0.0 */ interface TraceState { /** * Create a new TraceState which inherits from this TraceState and has the * given key set. * The new entry will always be added in the front of the list of states. * * @param key key of the TraceState entry. * @param value value of the TraceState entry. */ set(key: string, value: string): TraceState; /** * Return a new TraceState which inherits from this TraceState but does not * contain the given key. * * @param key the key for the TraceState entry to be removed. */ unset(key: string): TraceState; /** * Returns the value to which the specified key is mapped, or `undefined` if * this map contains no mapping for the key. * * @param key with which the specified value is to be associated. * @returns the value to which the specified key is mapped, or `undefined` if * this map contains no mapping for the key. */ get(key: string): string | undefined; /** * Serializes the TraceState to a `list` as defined below. The `list` is a * series of `list-members` separated by commas `,`, and a list-member is a * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs * surrounding `list-members` are ignored. There can be a maximum of 32 * `list-members` in a `list`. * * @returns the serialized string. */ serialize(): string; } /** * A SpanContext represents the portion of a {@link Span} which must be * serialized and propagated along side of a {@link Baggage}. * * @since 1.0.0 */ interface SpanContext { /** * The ID of the trace that this span belongs to. It is worldwide unique * with practically sufficient probability by being made as 16 randomly * generated bytes, encoded as a 32 lowercase hex characters corresponding to * 128 bits. */ traceId: string; /** * The ID of the Span. It is globally unique with practically sufficient * probability by being made as 8 randomly generated bytes, encoded as a 16 * lowercase hex characters corresponding to 64 bits. */ spanId: string; /** * Only true if the SpanContext was propagated from a remote parent. */ isRemote?: boolean; /** * Trace flags to propagate. * * It is represented as 1 byte (bitmap). Bit to represent whether trace is * sampled or not. When set, the least significant bit documents that the * caller may have recorded trace data. A caller who does not record trace * data out-of-band leaves this flag unset. * * see {@link TraceFlags} for valid flag values. */ traceFlags: number; /** * Tracing-system-specific info to propagate. * * The tracestate field value is a `list` as defined below. The `list` is a * series of `list-members` separated by commas `,`, and a list-member is a * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs * surrounding `list-members` are ignored. There can be a maximum of 32 * `list-members` in a `list`. * More Info: https://www.w3.org/TR/trace-context/#tracestate-field * * Examples: * Single tracing system (generic format): * tracestate: rojo=00f067aa0ba902b7 * Multiple tracing systems (with different formatting): * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE */ traceState?: TraceState; } /** * @since 1.0.0 */ interface SpanStatus { /** The status code of this message. */ code: SpanStatusCode; /** A developer-facing error message. */ message?: string; } /** * An enumeration of status codes. * * @since 1.0.0 */ declare enum SpanStatusCode { /** * The default status. */ UNSET = 0, /** * The operation has been validated by an Application developer or * Operator to have completed successfully. */ OK = 1, /** * The operation contains an error. */ ERROR = 2 } /** * A pointer from the current {@link Span} to another span in the same trace or * in a different trace. * Few examples of Link usage. * 1. Batch Processing: A batch of elements may contain elements associated * with one or more traces/spans. Since there can only be one parent * SpanContext, Link is used to keep reference to SpanContext of all * elements in the batch. * 2. Public Endpoint: A SpanContext in incoming client request on a public * endpoint is untrusted from service provider perspective. In such case it * is advisable to start a new trace with appropriate sampling decision. * However, it is desirable to associate incoming SpanContext to new trace * initiated on service provider side so two traces (from Client and from * Service Provider) can be correlated. * * @since 1.0.0 */ interface Link { /** The {@link SpanContext} of a linked span. */ context: SpanContext; /** A set of {@link SpanAttributes} on the link. */ attributes?: SpanAttributes; /** Count of attributes of the link that were dropped due to collection limits */ droppedAttributesCount?: number; } /** * An interface that represents a span. A span represents a single operation * within a trace. Examples of span might include remote procedure calls or a * in-process function calls to sub-components. A Trace has a single, top-level * "root" Span that in turn may have zero or more child Spans, which in turn * may have children. * * Spans are created by the {@link Tracer.startSpan} method. * * @since 1.0.0 */ interface Span { /** * Returns the {@link SpanContext} object associated with this Span. * * Get an immutable, serializable identifier for this span that can be used * to create new child spans. Returned SpanContext is usable even after the * span ends. * * @returns the SpanContext object associated with this Span. */ spanContext(): SpanContext; /** * Sets an attribute to the span. * * Sets a single Attribute with the key and value passed as arguments. * * @param key the key for this attribute. * @param value the value for this attribute. Setting a value null or * undefined is invalid and will result in undefined behavior. */ setAttribute(key: string, value: SpanAttributeValue): this; /** * Sets attributes to the span. * * @param attributes the attributes that will be added. * null or undefined attribute values * are invalid and will result in undefined behavior. */ setAttributes(attributes: SpanAttributes): this; /** * Adds an event to the Span. * * @param name the name of the event. * @param [attributesOrStartTime] the attributes that will be added; these are * associated with this event. Can be also a start time * if type is {@type TimeInput} and 3rd param is undefined * @param [startTime] start time of the event. */ addEvent(name: string, attributesOrStartTime?: SpanAttributes | TimeInput, startTime?: TimeInput): this; /** * Adds a single link to the span. * * Links added after the creation will not affect the sampling decision. * It is preferred span links be added at span creation. * * @param link the link to add. */ addLink(link: Link): this; /** * Adds multiple links to the span. * * Links added after the creation will not affect the sampling decision. * It is preferred span links be added at span creation. * * @param links the links to add. */ addLinks(links: Link[]): this; /** * Sets the status of the span. * * By default, a span has status {@link SpanStatusCode.UNSET}. * Calling this method overrides that default. * * The status codes have a total order: `OK > ERROR > UNSET`. * * - Once {@link SpanStatusCode.OK} is set, any further attempts to change * the status are ignored. * - Any attempt to set {@link SpanStatusCode.UNSET} is always ignored. * * The `message` field is only used when {@link SpanStatusCode.ERROR} is set. * For all other status codes, `message` is ignored. * * @param status The {@link SpanStatus} to set. */ setStatus(status: SpanStatus): this; /** * Updates the Span name. * * This will override the name provided via {@link Tracer.startSpan}. * * Upon this update, any sampling behavior based on Span name will depend on * the implementation. * * @param name the Span name. */ updateName(name: string): this; /** * Marks the end of Span execution. * * Call to End of a Span MUST not have any effects on child spans. Those may * still be running and can be ended later. * * Do not return `this`. The Span generally should not be used after it * is ended so chaining is not desired in this context. * * @param [endTime] the time to set as Span's end time. If not provided, * use the current time as the span's end time. */ end(endTime?: TimeInput): void; /** * Returns the flag whether this span will be recorded. * * @returns true if this Span is active and recording information like events * with the `AddEvent` operation and attributes using `setAttributes`. */ isRecording(): boolean; /** * Sets exception as a span event * @param exception the exception the only accepted values are string or Error * @param [time] the time to set as Span's event time. If not provided, * use the current time. */ recordException(exception: Exception, time?: TimeInput): void; } /** * @since 1.0.0 */ declare enum SpanKind { /** Default value. Indicates that the span is used internally. */ INTERNAL = 0, /** * Indicates that the span covers server-side handling of an RPC or other * remote request. */ SERVER = 1, /** * Indicates that the span covers the client-side wrapper around an RPC or * other remote request. */ CLIENT = 2, /** * Indicates that the span describes producer sending a message to a * broker. Unlike client and server, there is no direct critical path latency * relationship between producer and consumer spans. */ PRODUCER = 3, /** * Indicates that the span describes consumer receiving a message from a * broker. Unlike client and server, there is no direct critical path latency * relationship between producer and consumer spans. */ CONSUMER = 4 } /** * Options needed for span creation * * @since 1.0.0 */ interface SpanOptions { /** * The SpanKind of a span * @default {@link SpanKind.INTERNAL} */ kind?: SpanKind; /** A span's attributes */ attributes?: Attributes; /** {@link Link}s span to other spans */ links?: Link[]; /** A manually specified start time for the created `Span` object. */ startTime?: TimeInput; /** The new span should be a root span. (Ignore parent from context). */ root?: boolean; } /** * Tracer provides an interface for creating {@link Span}s. * * @since 1.0.0 */ interface Tracer { /** * Starts a new {@link Span}. Start the span without setting it on context. * * This method do NOT modify the current Context. * * @param name The name of the span * @param [options] SpanOptions used for span creation * @param [context] Context to use to extract parent * @returns Span The newly created span * @example * const span = tracer.startSpan('op'); * span.setAttribute('key', 'value'); * span.end(); */ startSpan(name: string, options?: SpanOptions, context?: Context): Span; /** * Starts a new {@link Span} and calls the given function passing it the * created span as first argument. * Additionally the new span gets set in context and this context is activated * for the duration of the function call. * * @param name The name of the span * @param [options] SpanOptions used for span creation * @param [context] Context to use to extract parent * @param fn function called in the context of the span and receives the newly created span as an argument * @returns return value of fn * @example * const something = tracer.startActiveSpan('op', span => { * try { * do some work * span.setStatus({code: SpanStatusCode.OK}); * return something; * } catch (err) { * span.setStatus({ * code: SpanStatusCode.ERROR, * message: err.message, * }); * throw err; * } finally { * span.end(); * } * }); * * @example * const span = tracer.startActiveSpan('op', span => { * try { * do some work * return span; * } catch (err) { * span.setStatus({ * code: SpanStatusCode.ERROR, * message: err.message, * }); * throw err; * } * }); * do some more work * span.end(); */ startActiveSpan unknown>(name: string, fn: F): ReturnType; startActiveSpan unknown>(name: string, options: SpanOptions, fn: F): ReturnType; startActiveSpan unknown>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType; } export { Attributes as A, Context as C, Tracer as T };