Skip to content

Commit 6ca6806

Browse files
committed
feat(server): force a new Sentry trace id for each request
1 parent dfc0daa commit 6ca6806

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

packages/server/src/middleware/sentry.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { _compasSentryExport } from "@compas/stdlib";
1+
import { _compasSentryExport, isNil, uuid } from "@compas/stdlib";
22

33
/**
44
* Sentry support;
@@ -21,28 +21,32 @@ export function sentry() {
2121
};
2222
}
2323

24-
return async (ctx, next) => {
24+
return (ctx, next) => {
2525
if (ctx.method === "OPTIONS" || ctx.method === "HEAD") {
2626
return next();
2727
}
2828

29-
let traceParentData = {
30-
forceTransaction: true,
31-
};
32-
if (ctx.request.get("sentry-trace")) {
33-
// @ts-expect-error
34-
traceParentData = _compasSentryExport.extractTraceparentData(
35-
ctx.request.get("sentry-trace"),
36-
);
29+
if (!_compasSentryExport) {
30+
return next();
3731
}
3832

39-
// @ts-expect-error
40-
return await _compasSentryExport.startSpanManual(
33+
const traceHeader = ctx.request.get("sentry-trace");
34+
/** @type {any} */
35+
const traceParentData =
36+
_compasSentryExport.extractTraceparentData(traceHeader) ?? {};
37+
38+
// Use a manual span, so we can end it right after the body is send.
39+
return _compasSentryExport.startSpanManual(
4140
{
41+
// Force a new trace for every request. This keeps the traces view usable.
42+
traceId: uuid().replace(/-/g, ""),
43+
...traceParentData,
44+
spanId: uuid().replace(/-/g, "").slice(16),
45+
forceTransaction: isNil(traceParentData.parentSpanId),
46+
4247
op: "http.server",
4348
name: "http",
4449
description: "http",
45-
...traceParentData,
4650
attributes: {
4751
"http.request.method": ctx.method,
4852
"http.request.url": ctx.url,

0 commit comments

Comments
 (0)