From 25bb7b75d538b26f1e77f42090066b99926b1e11 Mon Sep 17 00:00:00 2001 From: kristofferjansson Date: Fri, 8 Nov 2024 11:22:22 +0100 Subject: [PATCH] Add function to construct a new traceparent --- lib/traceparent.ts | 11 +++++++++++ test/unit/traceparent.test.ts | 24 +++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/traceparent.ts b/lib/traceparent.ts index f11acc6..7780e3f 100644 --- a/lib/traceparent.ts +++ b/lib/traceparent.ts @@ -1,3 +1,5 @@ +import crypto from "crypto"; + /** * Traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00 * @@ -17,3 +19,12 @@ export function getTraceFromTraceparent(traceHeader: string) { isSampled: parts[3] !== "00", }; } + +export function createTraceparent(isSampled: boolean = false) { + const version = "00"; + const traceId = crypto.randomBytes(16).toString("hex"); + const parentId = crypto.randomBytes(8).toString("hex"); + const flags = isSampled ? "01" : "00"; + + return `${version}-${traceId}-${parentId}-${flags}`; +} diff --git a/test/unit/traceparent.test.ts b/test/unit/traceparent.test.ts index e9fe8ac..e77c36f 100644 --- a/test/unit/traceparent.test.ts +++ b/test/unit/traceparent.test.ts @@ -1,4 +1,4 @@ -import { getTraceFromTraceparent } from "../../lib/traceparent"; +import { getTraceFromTraceparent, createTraceparent } from "../../lib/traceparent"; describe("Traceparent parsing", () => { it("should parse a traceparent header correctly", async () => { @@ -21,3 +21,25 @@ describe("Traceparent parsing", () => { expect(trace).to.equal(undefined); }); }); + +describe("Traceparent creation", () => { + it("should create a traceparent header correctly", async () => { + const traceparent = createTraceparent(); + const [version, traceId, parentId, isSampled] = traceparent.split("-"); + + expect(version).to.equal("00"); // we only support version 00 + expect(isSampled).to.equal("00"); // default is not sampled + + expect(new RegExp(/^[\da-f]{2}$/).test(version)).to.equal(true, version); + expect(new RegExp(/^[\da-f]{32}$/).test(traceId)).to.equal(true, traceId); + expect(new RegExp(/^[\da-f]{16}$/).test(parentId)).to.equal(true, parentId); + expect(new RegExp(/^[\da-f]{2}$/).test(isSampled)).to.equal(true, isSampled); + }); + + it("Sets flags if passed isSampled true", async () => { + const traceparent = createTraceparent(true); + const [, , , isSampled] = traceparent.split("-"); + + expect(isSampled).to.equal("01"); + }); +});