All files / src/utils traceId.ts

100% Statements 15/15
100% Branches 6/6
100% Functions 2/2
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 402x 2x   2x                     2x 2x 230x 230x 230x 230x 230x   2x                         2x 2x 55x 55x  
/** An OpenTelemetry trace id: 32 lowercase hex characters, not all zero. */
const TRACE_ID_PATTERN = /^(?!0{32}$)[0-9a-f]{32}$/;
 
/**
 * Generates a random OpenTelemetry trace id, used to tie together every log from one search.
 * It carries no information about the user or the query.
 * @category Utils
 * @group Types
 * @returns 32 lowercase hex characters
 * @example
 * ```typescript
 * generateTraceId(); // '4bf92f3577b34da6a3ce929d0e0e4736'
 * ```
 * @source
 */
export function generateTraceId(): string {
  const bytes = crypto.getRandomValues(new Uint8Array(16));
  const id = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
  // An all-zero id is invalid in OpenTelemetry (a 1-in-2^128 chance, but cheap to rule out).
  return TRACE_ID_PATTERN.test(id) ? id : generateTraceId();
}
 
/**
 * Whether a value is a well-formed trace id, so a malformed one is never sent as the `trace_id`.
 * @category Utils
 * @group Types
 * @param value - The value to test
 * @returns `true` for 32 lowercase hex characters that are not all zero
 * @example
 * ```typescript
 * isTraceId('4bf92f3577b34da6a3ce929d0e0e4736'); // true
 * isTraceId('00000000000000000000000000000000'); // false
 * isTraceId('not-a-trace-id');                   // false
 * ```
 * @source
 */
export function isTraceId(value: unknown): value is string {
  return typeof value === 'string' && TRACE_ID_PATTERN.test(value);
}