@dash0/sdk-web 0.14.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +77 -6
  2. package/dist/dash0.iife.js +1 -1
  3. package/dist/dash0.iife.js.map +1 -1
  4. package/dist/dash0.js +1 -1
  5. package/dist/dash0.js.map +1 -1
  6. package/dist/dash0.umd.cjs +1 -1
  7. package/dist/dash0.umd.cjs.map +1 -1
  8. package/dist/modules/api/init.js +30 -0
  9. package/dist/modules/api/init_test.js +102 -6
  10. package/dist/modules/instrumentations/http/fetch.js +47 -5
  11. package/dist/modules/instrumentations/http/fetch_test.js +170 -0
  12. package/dist/modules/instrumentations/http/propagator-integration_test.js +77 -0
  13. package/dist/modules/transport/index.js +1 -3
  14. package/dist/modules/utils/otel/trace-context.js +24 -1
  15. package/dist/modules/utils/otel/trace-context_test.js +40 -0
  16. package/dist/modules/utils/rate-limit.js +1 -5
  17. package/dist/tsconfig.tsbuildinfo +1 -1
  18. package/dist/types/entrypoint/npm-package.d.ts +1 -1
  19. package/dist/types/instrumentations/http/fetch_test.d.ts +1 -0
  20. package/dist/types/instrumentations/http/propagator-integration_test.d.ts +1 -0
  21. package/dist/types/types/options.d.ts +6 -1
  22. package/dist/types/utils/otel/trace-context.d.ts +2 -1
  23. package/dist/types/utils/otel/trace-context_test.d.ts +1 -0
  24. package/dist/types/utils/rate-limit.d.ts +0 -1
  25. package/dist/types/vars.d.ts +11 -0
  26. package/package.json +1 -1
  27. package/src/api/init.ts +34 -0
  28. package/src/api/init_test.ts +130 -9
  29. package/src/entrypoint/npm-package.ts +1 -1
  30. package/src/instrumentations/http/fetch.ts +59 -6
  31. package/src/instrumentations/http/fetch_test.ts +191 -0
  32. package/src/instrumentations/http/propagator-integration_test.ts +93 -0
  33. package/src/transport/index.ts +1 -3
  34. package/src/types/options.ts +7 -1
  35. package/src/utils/otel/trace-context.ts +30 -1
  36. package/src/utils/otel/trace-context_test.ts +59 -0
  37. package/src/utils/rate-limit.ts +2 -12
  38. package/src/vars.ts +14 -0
@@ -40,6 +40,7 @@ export function init(opts) {
40
40
  "urlAttributeScrubber",
41
41
  "pageViewInstrumentation",
42
42
  ])));
43
+ initializePropagators(opts);
43
44
  initializeResourceAttributes(opts);
44
45
  initializeSignalAttributes(opts);
45
46
  initializeTabId();
@@ -137,6 +138,35 @@ function detectDeploymentId(opts) {
137
138
  return undefined;
138
139
  }
139
140
  }
141
+ function initializePropagators(opts) {
142
+ if (opts.propagators) {
143
+ if (opts.propagateTraceHeadersCorsURLs) {
144
+ warn("Both 'propagators' and deprecated 'propagateTraceHeadersCorsURLs' were provided. Using 'propagators' configuration. Please migrate to the new 'propagators' config.");
145
+ }
146
+ vars.propagators = opts.propagators;
147
+ }
148
+ // Handle legacy configuration
149
+ else if (opts.propagateTraceHeadersCorsURLs && opts.propagateTraceHeadersCorsURLs.length > 0) {
150
+ warn("'propagateTraceHeadersCorsURLs' is deprecated. Please use the new 'propagators' configuration.");
151
+ // Convert legacy config to new format - only include cross-origin URLs since same-origin is automatic
152
+ vars.propagators = [
153
+ {
154
+ type: "traceparent",
155
+ match: [...opts.propagateTraceHeadersCorsURLs],
156
+ },
157
+ ];
158
+ }
159
+ // Default configuration - traceparent with empty match array
160
+ // Same-origin requests get ALL configured propagators, so this ensures traceparent for same-origin
161
+ else {
162
+ vars.propagators = [
163
+ {
164
+ type: "traceparent",
165
+ match: [],
166
+ },
167
+ ];
168
+ }
169
+ }
140
170
  function isInstrumentationEnabled(name, opts) {
141
171
  const instrumentations = opts.enabledInstrumentations;
142
172
  if (!instrumentations)
@@ -1,4 +1,4 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
2
  // Mock all the instrumentation modules
3
3
  vi.mock("../instrumentations/web-vitals", () => ({
4
4
  startWebVitalsInstrumentation: vi.fn(),
@@ -12,26 +12,34 @@ vi.mock("../instrumentations/http/fetch", () => ({
12
12
  vi.mock("../instrumentations/navigation", () => ({
13
13
  startNavigationInstrumentation: vi.fn(),
14
14
  }));
15
- import { startWebVitalsInstrumentation } from "../instrumentations/web-vitals";
16
15
  import { startErrorInstrumentation } from "../instrumentations/errors";
17
16
  import { instrumentFetch } from "../instrumentations/http/fetch";
18
17
  import { startNavigationInstrumentation } from "../instrumentations/navigation";
18
+ import { startWebVitalsInstrumentation } from "../instrumentations/web-vitals";
19
19
  describe("init", () => {
20
20
  const baseOptions = {
21
21
  serviceName: "test-service",
22
22
  endpoint: { url: "https://test-endpoint.com", authToken: "invalid" },
23
23
  };
24
- beforeEach(() => {
24
+ let vars;
25
+ let init;
26
+ beforeEach(async () => {
25
27
  vi.clearAllMocks();
26
28
  // Reset the hasBeenInitialised flag by re-importing the module
27
29
  vi.resetModules();
30
+ // Reset vars state after module reset
31
+ // since init itself needs vars, this needs to imported again as well.
32
+ // Otherwise the tests that make assumptions on the vars fail because they use a different reference.
33
+ const { vars: importedVars } = await import("../vars");
34
+ const { init: importedInit } = await import("./init");
35
+ vars = importedVars;
36
+ init = importedInit;
28
37
  });
29
38
  afterEach(() => {
30
39
  vi.clearAllMocks();
31
40
  });
32
41
  describe("instrumentation enablement", () => {
33
42
  it("should enable all instrumentations when enabledInstrumentations is undefined", async () => {
34
- const { init } = await import("./init");
35
43
  init({
36
44
  ...baseOptions,
37
45
  enabledInstrumentations: undefined,
@@ -55,7 +63,6 @@ describe("init", () => {
55
63
  };
56
64
  instrumentations.forEach((instrumentation) => {
57
65
  it(`should enable ${instrumentation} instrumentation when present in enabledInstrumentations array`, async () => {
58
- const { init } = await import("./init");
59
66
  init({
60
67
  ...baseOptions,
61
68
  enabledInstrumentations: [instrumentation],
@@ -69,7 +76,6 @@ describe("init", () => {
69
76
  });
70
77
  });
71
78
  it(`should not enable ${instrumentation} instrumentation when not present in enabledInstrumentations array`, async () => {
72
- const { init } = await import("./init");
73
79
  const otherInstrumentations = instrumentations.filter((i) => i !== instrumentation);
74
80
  init({
75
81
  ...baseOptions,
@@ -83,4 +89,94 @@ describe("init", () => {
83
89
  });
84
90
  });
85
91
  });
92
+ describe("propagator configuration", () => {
93
+ it("should set propagators configuration when provided", async () => {
94
+ const propagators = [
95
+ { type: "traceparent", match: [/.*\/api\/.*/] },
96
+ { type: "xray", match: [/.*\.amazonaws\.com.*/] },
97
+ ];
98
+ init({
99
+ ...baseOptions,
100
+ propagators,
101
+ });
102
+ expect(vars.propagators).toEqual(propagators);
103
+ });
104
+ it("should warn when both propagators and legacy config are provided", async () => {
105
+ const spyOnWarn = vi.spyOn(console, "warn");
106
+ const propagators = [{ type: "traceparent", match: [/.*\/api\/.*/] }];
107
+ init({
108
+ ...baseOptions,
109
+ propagators,
110
+ propagateTraceHeadersCorsURLs: [/.*\.example\.com.*/],
111
+ });
112
+ expect(spyOnWarn).toHaveBeenCalledWith("Both 'propagators' and deprecated 'propagateTraceHeadersCorsURLs' were provided. Using 'propagators' configuration. Please migrate to the new 'propagators' config.");
113
+ expect(vars.propagators).toEqual(propagators);
114
+ });
115
+ it("should convert legacy config to new format with deprecation warning", async () => {
116
+ const spyOnWarn = vi.spyOn(console, "warn");
117
+ const legacyConfig = [/.*\.example\.com.*/, /.*\.test\.com.*/];
118
+ init({
119
+ ...baseOptions,
120
+ propagateTraceHeadersCorsURLs: legacyConfig,
121
+ });
122
+ expect(spyOnWarn).toHaveBeenCalledWith("'propagateTraceHeadersCorsURLs' is deprecated. Please use the new 'propagators' configuration.");
123
+ expect(vars.propagators).toEqual([
124
+ {
125
+ type: "traceparent",
126
+ match: [...legacyConfig],
127
+ },
128
+ ]);
129
+ });
130
+ it("should set default propagators when no configuration is provided", async () => {
131
+ init(baseOptions);
132
+ expect(vars.propagators).toEqual([
133
+ {
134
+ type: "traceparent",
135
+ match: [],
136
+ },
137
+ ]);
138
+ });
139
+ it("should not convert empty legacy config", async () => {
140
+ const spyOnWarn = vi.spyOn(console, "warn");
141
+ init({
142
+ ...baseOptions,
143
+ propagateTraceHeadersCorsURLs: [],
144
+ });
145
+ expect(spyOnWarn).not.toHaveBeenCalled();
146
+ expect(vars.propagators).toEqual([
147
+ {
148
+ type: "traceparent",
149
+ match: [],
150
+ },
151
+ ]);
152
+ });
153
+ it("should handle mixed pattern types in propagators", async () => {
154
+ const spyOnWarn = vi.spyOn(console, "warn");
155
+ const propagators = [
156
+ {
157
+ type: "traceparent",
158
+ match: [/.*\/api\/.*/],
159
+ },
160
+ {
161
+ type: "xray",
162
+ match: [/.*\.amazonaws\.com.*/, /.*\.aws\.com.*/],
163
+ },
164
+ ];
165
+ init({
166
+ ...baseOptions,
167
+ propagators,
168
+ });
169
+ expect(vars.propagators).toEqual(propagators);
170
+ expect(spyOnWarn).not.toHaveBeenCalled();
171
+ });
172
+ it("should handle empty propagators array", async () => {
173
+ const spyOnWarn = vi.spyOn(console, "warn");
174
+ init({
175
+ ...baseOptions,
176
+ propagators: [],
177
+ });
178
+ expect(vars.propagators).toEqual([]);
179
+ expect(spyOnWarn).not.toHaveBeenCalled();
180
+ });
181
+ });
86
182
  });
@@ -1,6 +1,6 @@
1
1
  import { debug, observeResourcePerformance, win } from "../../utils";
2
2
  import { isUrlIgnored, matchesAny } from "../../utils/ignore-rules";
3
- import { addAttribute, setSpanStatus, addTraceContextHttpHeaders, endSpan, errorToSpanStatus, recordException, startSpan, } from "../../utils/otel";
3
+ import { addAttribute, setSpanStatus, addW3CTraceContextHttpHeaders, addXRayTraceContextHttpHeaders, endSpan, errorToSpanStatus, recordException, startSpan, } from "../../utils/otel";
4
4
  import { ERROR_TYPE, HTTP_REQUEST_METHOD, HTTP_REQUEST_METHOD_ORIGINAL, HTTP_RESPONSE_STATUS_CODE, SPAN_STATUS_ERROR, SPAN_STATUS_UNSET, } from "../../semantic-conventions";
5
5
  import { isSameOrigin, wrap, parseUrl } from "../../utils";
6
6
  import { vars } from "../../vars";
@@ -47,22 +47,23 @@ function wrapFetch(original) {
47
47
  if (!isWellKnownMethod) {
48
48
  addAttribute(span.attributes, HTTP_REQUEST_METHOD_ORIGINAL, originalMethod);
49
49
  }
50
- const shouldSetCorrelationHeaders = isSameOrigin(url) || matchesAny(vars.propagateTraceHeadersCorsURLs, url);
50
+ const propagatorTypes = determinePropagatorTypes(url);
51
+ const shouldSetCorrelationHeaders = propagatorTypes.length > 0;
51
52
  if (shouldSetCorrelationHeaders) {
52
53
  if (copyOfInit?.headers) {
53
54
  // ensure we have a unified container for the headers
54
55
  copyOfInit.headers = new Headers(copyOfInit.headers);
55
- addTraceContextHttpHeaders(copyOfInit.headers.append, copyOfInit.headers, span);
56
+ addTraceContextHttpHeaders(copyOfInit.headers.append, copyOfInit.headers, span, propagatorTypes);
56
57
  }
57
58
  else if (input instanceof Request) {
58
- addTraceContextHttpHeaders(request.headers.append, request.headers, span);
59
+ addTraceContextHttpHeaders(request.headers.append, request.headers, span, propagatorTypes);
59
60
  }
60
61
  else {
61
62
  if (!copyOfInit) {
62
63
  copyOfInit = {};
63
64
  }
64
65
  copyOfInit.headers = new Headers();
65
- addTraceContextHttpHeaders(copyOfInit.headers.append, copyOfInit.headers, span);
66
+ addTraceContextHttpHeaders(copyOfInit.headers.append, copyOfInit.headers, span, propagatorTypes);
66
67
  }
67
68
  }
68
69
  tryCaptureHttpHeaders(request.headers, span, (k) => httpRequestHeaderKey(k));
@@ -165,3 +166,44 @@ function endSpanOnError(span, error) {
165
166
  recordException(span, error);
166
167
  sendSpan(endSpan(span, errorToSpanStatus(error), undefined));
167
168
  }
169
+ function determinePropagatorTypes(url) {
170
+ const matchingTypes = [];
171
+ const isUrlSameOrigin = isSameOrigin(url);
172
+ // For same-origin requests, always include traceparent + all configured propagators
173
+ if (isUrlSameOrigin) {
174
+ // Always add traceparent for same-origin requests
175
+ matchingTypes.push("traceparent");
176
+ // Add all other configured propagator types for same-origin requests
177
+ if (vars.propagators) {
178
+ for (const propagator of vars.propagators) {
179
+ if (propagator.type !== "traceparent" && !matchingTypes.includes(propagator.type)) {
180
+ matchingTypes.push(propagator.type);
181
+ }
182
+ }
183
+ }
184
+ return matchingTypes;
185
+ }
186
+ // For cross-origin requests, use new propagators config if available
187
+ if (vars.propagators) {
188
+ for (const propagator of vars.propagators) {
189
+ if (matchesAny(propagator.match, url)) {
190
+ // Avoid duplicates
191
+ if (!matchingTypes.includes(propagator.type)) {
192
+ matchingTypes.push(propagator.type);
193
+ }
194
+ }
195
+ }
196
+ return matchingTypes;
197
+ }
198
+ return [];
199
+ }
200
+ function addTraceContextHttpHeaders(fn, ctx, span, types) {
201
+ for (const type of types) {
202
+ if (type === "xray") {
203
+ addXRayTraceContextHttpHeaders(fn, ctx, span);
204
+ }
205
+ else {
206
+ addW3CTraceContextHttpHeaders(fn, ctx, span);
207
+ }
208
+ }
209
+ }
@@ -0,0 +1,170 @@
1
+ import { expect, vi, beforeEach, afterEach } from "vitest";
2
+ import { vars } from "../../vars";
3
+ import { instrumentFetch } from "./fetch";
4
+ describe("fetch test", () => {
5
+ let fetchMock;
6
+ beforeEach(() => {
7
+ fetchMock = vi.fn(() => ({
8
+ ok: false,
9
+ headers: new Headers(),
10
+ status: 200,
11
+ clone: () => ({
12
+ body: null,
13
+ }),
14
+ }));
15
+ vi.stubGlobal("fetch", fetchMock);
16
+ vi.stubGlobal("location", { origin: "http://localhost:3000" });
17
+ });
18
+ afterEach(() => {
19
+ vi.resetAllMocks();
20
+ vars.propagators = undefined;
21
+ });
22
+ it("should inject traceparent header for cross-origin requests", async () => {
23
+ vars.propagators = [
24
+ {
25
+ type: "traceparent",
26
+ match: [new RegExp("http://foo.bar/")],
27
+ },
28
+ ];
29
+ instrumentFetch();
30
+ // eslint-disable-next-line no-restricted-globals
31
+ await fetch("http://foo.bar/foo");
32
+ expect(fetchMock).toHaveBeenCalledOnce();
33
+ const fetchHeaders = fetchMock.mock.calls[0].at(1).headers;
34
+ expect(fetchHeaders.get("traceparent")).not.toBeNull();
35
+ });
36
+ it("should inject xray header for cross-origin requests", async () => {
37
+ vars.propagators = [
38
+ {
39
+ type: "xray",
40
+ match: [new RegExp("http://foo.bar/")],
41
+ },
42
+ ];
43
+ instrumentFetch();
44
+ // eslint-disable-next-line no-restricted-globals
45
+ await fetch("http://foo.bar/foo");
46
+ expect(fetchMock).toHaveBeenCalledOnce();
47
+ const fetchHeaders = fetchMock.mock.calls[0].at(1).headers;
48
+ expect(fetchHeaders.get("X-Amzn-Trace-Id")).not.toBeNull();
49
+ });
50
+ it("should inject both headers for cross-origin requests when both match", async () => {
51
+ vars.propagators = [
52
+ {
53
+ type: "traceparent",
54
+ match: [new RegExp("http://foo.bar/")],
55
+ },
56
+ {
57
+ type: "xray",
58
+ match: [new RegExp("http://foo.bar/")],
59
+ },
60
+ ];
61
+ instrumentFetch();
62
+ // eslint-disable-next-line no-restricted-globals
63
+ await fetch("http://foo.bar/foo");
64
+ expect(fetchMock).toHaveBeenCalledOnce();
65
+ const fetchHeaders = fetchMock.mock.calls[0].at(1).headers;
66
+ expect(fetchHeaders.get("X-Amzn-Trace-Id")).not.toBeNull();
67
+ expect(fetchHeaders.get("traceparent")).not.toBeNull();
68
+ });
69
+ it("should inject no headers for non-matching cross-origin requests", async () => {
70
+ vars.propagators = [];
71
+ instrumentFetch();
72
+ // eslint-disable-next-line no-restricted-globals
73
+ await fetch("http://foo.bar/foo");
74
+ expect(fetchMock).toHaveBeenCalledOnce();
75
+ const expectedHeaders = undefined;
76
+ expect(fetchMock).toHaveBeenCalledWith("http://foo.bar/foo", expectedHeaders);
77
+ });
78
+ // New same-origin behavior tests
79
+ it("should inject all configured propagator headers for same-origin requests", async () => {
80
+ vars.propagators = [
81
+ {
82
+ type: "traceparent",
83
+ match: [new RegExp("http://foo.bar/")], // Doesn't match same-origin
84
+ },
85
+ {
86
+ type: "xray",
87
+ match: [new RegExp("http://baz.com/")], // Doesn't match same-origin
88
+ },
89
+ ];
90
+ instrumentFetch();
91
+ // Same-origin request
92
+ // eslint-disable-next-line no-restricted-globals
93
+ await fetch("http://localhost:3000/api/test");
94
+ expect(fetchMock).toHaveBeenCalledOnce();
95
+ const fetchHeaders = fetchMock.mock.calls[0].at(1).headers;
96
+ // Both headers should be present for same-origin, regardless of match patterns
97
+ expect(fetchHeaders.get("traceparent")).not.toBeNull();
98
+ expect(fetchHeaders.get("X-Amzn-Trace-Id")).not.toBeNull();
99
+ });
100
+ it("should inject only traceparent for same-origin when only traceparent propagator configured", async () => {
101
+ vars.propagators = [
102
+ {
103
+ type: "traceparent",
104
+ match: [new RegExp("http://foo.bar/")],
105
+ },
106
+ ];
107
+ instrumentFetch();
108
+ // Same-origin request
109
+ // eslint-disable-next-line no-restricted-globals
110
+ await fetch("http://localhost:3000/api/test");
111
+ expect(fetchMock).toHaveBeenCalledOnce();
112
+ const fetchHeaders = fetchMock.mock.calls[0].at(1).headers;
113
+ expect(fetchHeaders.get("traceparent")).not.toBeNull();
114
+ expect(fetchHeaders.get("X-Amzn-Trace-Id")).toBeNull();
115
+ });
116
+ it("should inject both traceparent and xray for same-origin when only xray propagator configured", async () => {
117
+ vars.propagators = [
118
+ {
119
+ type: "xray",
120
+ match: [new RegExp("http://foo.bar/")],
121
+ },
122
+ ];
123
+ instrumentFetch();
124
+ // Same-origin request
125
+ // eslint-disable-next-line no-restricted-globals
126
+ await fetch("http://localhost:3000/api/test");
127
+ expect(fetchMock).toHaveBeenCalledOnce();
128
+ const fetchHeaders = fetchMock.mock.calls[0].at(1).headers;
129
+ // Same-origin always gets traceparent + all configured propagator types
130
+ expect(fetchHeaders.get("traceparent")).not.toBeNull();
131
+ expect(fetchHeaders.get("X-Amzn-Trace-Id")).not.toBeNull();
132
+ });
133
+ it("should inject traceparent for same-origin when default traceparent propagator configured", async () => {
134
+ vars.propagators = [
135
+ {
136
+ type: "traceparent",
137
+ match: [], // Empty match array - matches no cross-origin URLs but same-origin gets all propagators
138
+ },
139
+ ];
140
+ instrumentFetch();
141
+ // Same-origin request
142
+ // eslint-disable-next-line no-restricted-globals
143
+ await fetch("http://localhost:3000/api/test");
144
+ expect(fetchMock).toHaveBeenCalledOnce();
145
+ const fetchHeaders = fetchMock.mock.calls[0].at(1).headers;
146
+ // Same-origin gets all configured propagator types
147
+ expect(fetchHeaders.get("traceparent")).not.toBeNull();
148
+ expect(fetchHeaders.get("X-Amzn-Trace-Id")).toBeNull();
149
+ });
150
+ it("should follow cross-origin pattern matching for non-same-origin requests", async () => {
151
+ vars.propagators = [
152
+ {
153
+ type: "traceparent",
154
+ match: [new RegExp("http://foo.bar/")],
155
+ },
156
+ {
157
+ type: "xray",
158
+ match: [new RegExp("http://baz.com/")],
159
+ },
160
+ ];
161
+ instrumentFetch();
162
+ // Cross-origin request that matches only traceparent pattern
163
+ // eslint-disable-next-line no-restricted-globals
164
+ await fetch("http://foo.bar/api");
165
+ expect(fetchMock).toHaveBeenCalledOnce();
166
+ const fetchHeaders = fetchMock.mock.calls[0].at(1).headers;
167
+ expect(fetchHeaders.get("traceparent")).not.toBeNull();
168
+ expect(fetchHeaders.get("X-Amzn-Trace-Id")).toBeNull();
169
+ });
170
+ });
@@ -0,0 +1,77 @@
1
+ import { describe, it, expect, beforeEach } from "vitest";
2
+ import { addW3CTraceContextHttpHeaders, addXRayTraceContextHttpHeaders } from "../../utils/otel/trace-context";
3
+ describe("Multiple propagator integration", () => {
4
+ let headers;
5
+ let mockAppend;
6
+ let mockSpan;
7
+ beforeEach(() => {
8
+ headers = {};
9
+ mockAppend = (name, value) => {
10
+ headers[name] = value;
11
+ };
12
+ mockSpan = {
13
+ traceId: "4efaaf4d1e8720b39541901950019ee5",
14
+ spanId: "53995c3f42cd8ad8",
15
+ attributes: [],
16
+ };
17
+ });
18
+ it("should add both W3C traceparent and X-Ray headers when both propagators match", () => {
19
+ // Simulate what happens when both propagator types are matched
20
+ const propagatorTypes = ["traceparent", "xray"];
21
+ // Add headers for each type (this simulates addHeadersBasedOnTypes)
22
+ for (const type of propagatorTypes) {
23
+ if (type === "xray") {
24
+ addXRayTraceContextHttpHeaders(mockAppend, {}, mockSpan);
25
+ }
26
+ else if (type === "traceparent") {
27
+ addW3CTraceContextHttpHeaders(mockAppend, {}, mockSpan);
28
+ }
29
+ }
30
+ // Verify both headers were added
31
+ expect(headers).toHaveProperty("traceparent");
32
+ expect(headers).toHaveProperty("X-Amzn-Trace-Id");
33
+ // Verify header formats
34
+ expect(headers["traceparent"]).toBe("00-4efaaf4d1e8720b39541901950019ee5-53995c3f42cd8ad8-01");
35
+ expect(headers["X-Amzn-Trace-Id"]).toBe("Root=1-4efaaf4d-1e8720b39541901950019ee5;Parent=53995c3f42cd8ad8;Sampled=1");
36
+ });
37
+ it("should only add W3C header when only traceparent propagator matches", () => {
38
+ const propagatorTypes = ["traceparent"];
39
+ for (const type of propagatorTypes) {
40
+ if (type === "xray") {
41
+ addXRayTraceContextHttpHeaders(mockAppend, {}, mockSpan);
42
+ }
43
+ else if (type === "traceparent") {
44
+ addW3CTraceContextHttpHeaders(mockAppend, {}, mockSpan);
45
+ }
46
+ }
47
+ expect(headers).toHaveProperty("traceparent");
48
+ expect(headers).not.toHaveProperty("X-Amzn-Trace-Id");
49
+ });
50
+ it("should only add X-Ray header when only xray propagator matches", () => {
51
+ const propagatorTypes = ["xray"];
52
+ for (const type of propagatorTypes) {
53
+ if (type === "xray") {
54
+ addXRayTraceContextHttpHeaders(mockAppend, {}, mockSpan);
55
+ }
56
+ else if (type === "traceparent") {
57
+ addW3CTraceContextHttpHeaders(mockAppend, {}, mockSpan);
58
+ }
59
+ }
60
+ expect(headers).not.toHaveProperty("traceparent");
61
+ expect(headers).toHaveProperty("X-Amzn-Trace-Id");
62
+ });
63
+ it("should handle Headers object correctly", () => {
64
+ const headersObj = new Headers();
65
+ const propagatorTypes = ["traceparent", "xray"];
66
+ for (const type of propagatorTypes) {
67
+ if (type === "xray") {
68
+ addXRayTraceContextHttpHeaders(headersObj.append.bind(headersObj), headersObj, mockSpan);
69
+ }
70
+ else if (type === "traceparent") {
71
+ addW3CTraceContextHttpHeaders(headersObj.append.bind(headersObj), headersObj, mockSpan);
72
+ }
73
+ }
74
+ expect(headersObj.get("traceparent")).toBe("00-4efaaf4d1e8720b39541901950019ee5-53995c3f42cd8ad8-01");
75
+ expect(headersObj.get("X-Amzn-Trace-Id")).toBe("Root=1-4efaaf4d-1e8720b39541901950019ee5;Parent=53995c3f42cd8ad8;Sampled=1");
76
+ });
77
+ });
@@ -1,15 +1,13 @@
1
1
  import { newBatcher } from "./batcher";
2
2
  import { send } from "./fetch";
3
3
  import { vars } from "../vars";
4
- import { createRateLimiter } from "../utils/rate-limit";
5
- import { debug, error } from "../utils";
4
+ import { debug, error, createRateLimiter } from "../utils";
6
5
  const logBatcher = newBatcher(sendLogs);
7
6
  const spanBatcher = newBatcher(sendSpans);
8
7
  let rateLimiter;
9
8
  function isRateLimited() {
10
9
  if (!rateLimiter) {
11
10
  rateLimiter = createRateLimiter({
12
- maxCalls: 8096,
13
11
  maxCallsPerTenMinutes: 4096,
14
12
  maxCallsPerTenSeconds: 128,
15
13
  });
@@ -39,7 +39,7 @@ function getTraceparentFromServerTiming(serverTimings) {
39
39
  }
40
40
  return "";
41
41
  }
42
- export function addTraceContextHttpHeaders(fn, ctx, span) {
42
+ export function addW3CTraceContextHttpHeaders(fn, ctx, span) {
43
43
  /**
44
44
  * W3C Traceparent header.
45
45
  * General format is ${version}-${trace-id}-${parent-id}-${trace-flags}
@@ -60,3 +60,26 @@ export function addTraceContextHttpHeaders(fn, ctx, span) {
60
60
  */
61
61
  fn.call(ctx, "traceparent", `00-${span.traceId}-${span.spanId}-01`);
62
62
  }
63
+ export function addXRayTraceContextHttpHeaders(fn, ctx, span) {
64
+ /**
65
+ * AWS X-Ray trace header.
66
+ * General format is Root=${trace-id};Parent=${span-id};Sampled=${sampling-flag}
67
+ *
68
+ * Converts W3C trace ID format to X-Ray format:
69
+ * W3C: 4efaaf4d1e8720b39541901950019ee5 (32 hex chars)
70
+ * X-Ray: 1-4efaaf4d-1e8720b39541901950019ee5 (1-{8chars}-{24chars})
71
+ *
72
+ * References:
73
+ * https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader
74
+ */
75
+ const xrayTraceId = convertW3CTraceIdToXRay(span.traceId);
76
+ const xrayHeader = `Root=${xrayTraceId};Parent=${span.spanId};Sampled=1`;
77
+ fn.call(ctx, "X-Amzn-Trace-Id", xrayHeader);
78
+ }
79
+ function convertW3CTraceIdToXRay(w3cTraceId) {
80
+ // X-Ray trace ID format: 1-{timestamp}-{unique-id}
81
+ // Split the 32-char W3C trace ID into 8-char timestamp and 24-char unique ID
82
+ const timestamp = w3cTraceId.substring(0, 8);
83
+ const uniqueId = w3cTraceId.substring(8, 32);
84
+ return `1-${timestamp}-${uniqueId}`;
85
+ }
@@ -0,0 +1,40 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { addXRayTraceContextHttpHeaders } from "./trace-context";
3
+ describe("X-Ray trace context", () => {
4
+ it("should generate X-Ray header with correct format", () => {
5
+ const span = {
6
+ traceId: "4efaaf4d1e8720b39541901950019ee5",
7
+ spanId: "53995c3f42cd8ad8",
8
+ };
9
+ const headers = {};
10
+ const mockAppend = (name, value) => {
11
+ headers[name] = value;
12
+ };
13
+ addXRayTraceContextHttpHeaders(mockAppend, {}, span);
14
+ expect(headers["X-Amzn-Trace-Id"]).toBe("Root=1-4efaaf4d-1e8720b39541901950019ee5;Parent=53995c3f42cd8ad8;Sampled=1");
15
+ });
16
+ it("should convert W3C trace ID to X-Ray format correctly", () => {
17
+ const span = {
18
+ traceId: "5759e988bd862e3fe1be46a994272793",
19
+ spanId: "53995c3f42cd8ad8",
20
+ };
21
+ const headers = {};
22
+ const mockAppend = (name, value) => {
23
+ headers[name] = value;
24
+ };
25
+ addXRayTraceContextHttpHeaders(mockAppend, {}, span);
26
+ expect(headers["X-Amzn-Trace-Id"]).toBe("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1");
27
+ });
28
+ it("should handle different span IDs", () => {
29
+ const span = {
30
+ traceId: "4efaaf4d1e8720b39541901950019ee5",
31
+ spanId: "1234567890abcdef",
32
+ };
33
+ const headers = {};
34
+ const mockAppend = (name, value) => {
35
+ headers[name] = value;
36
+ };
37
+ addXRayTraceContextHttpHeaders(mockAppend, {}, span);
38
+ expect(headers["X-Amzn-Trace-Id"]).toBe("Root=1-4efaaf4d-1e8720b39541901950019ee5;Parent=1234567890abcdef;Sampled=1");
39
+ });
40
+ });
@@ -1,9 +1,7 @@
1
1
  import { setInterval } from "./timers";
2
2
  export function createRateLimiter(opts) {
3
- const maxCalls = opts.maxCalls || 4096;
4
3
  const maxCallsPerTenMinutes = opts.maxCallsPerTenMinutes || 128;
5
4
  const maxCallsPerTenSeconds = opts.maxCallsPerTenSeconds || 32;
6
- let totalCalls = 0;
7
5
  let totalCallsInLastTenMinutes = 0;
8
6
  let totalCallsInLastTenSeconds = 0;
9
7
  setInterval(function () {
@@ -13,8 +11,6 @@ export function createRateLimiter(opts) {
13
11
  totalCallsInLastTenSeconds = 0;
14
12
  }, 1000 * 10);
15
13
  return function isExcessiveUsage() {
16
- return (++totalCalls > maxCalls ||
17
- ++totalCallsInLastTenMinutes > maxCallsPerTenMinutes ||
18
- ++totalCallsInLastTenSeconds > maxCallsPerTenSeconds);
14
+ return ++totalCallsInLastTenMinutes > maxCallsPerTenMinutes || ++totalCallsInLastTenSeconds > maxCallsPerTenSeconds;
19
15
  };
20
16
  }