Skip to content

Commit

Permalink
Add function to construct a new traceparent
Browse files Browse the repository at this point in the history
  • Loading branch information
kristofferjansson committed Nov 8, 2024
1 parent d61e138 commit 25bb7b7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
11 changes: 11 additions & 0 deletions lib/traceparent.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import crypto from "crypto";

/**
* Traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00
*
Expand All @@ -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}`;
}
24 changes: 23 additions & 1 deletion test/unit/traceparent.test.ts
Original file line number Diff line number Diff line change
@@ -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 () => {
Expand All @@ -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");
});
});

0 comments on commit 25bb7b7

Please sign in to comment.