@sentry/server-utils 11.20.0 → 11.22.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.
- package/build/cjs/chunks/config.js +30 -0
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +10 -1
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +381 -16
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/tanstack-ai/constants.js +11 -0
- package/build/esm/ai/tanstack-ai/constants.js.map +1 -0
- package/build/esm/ai/tanstack-ai/index.js +206 -0
- package/build/esm/ai/tanstack-ai/index.js.map +1 -0
- package/build/esm/ai/tanstack-ai/utils.js +81 -0
- package/build/esm/ai/tanstack-ai/utils.js.map +1 -0
- package/build/esm/ai/workers-ai/utils.js +4 -1
- package/build/esm/ai/workers-ai/utils.js.map +1 -1
- package/build/esm/index.js +2 -1
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/fastify/instrumentation.js +5 -1
- package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/neon.js +10 -2
- package/build/esm/integrations/neon.js.map +1 -1
- package/build/esm/integrations/pg.js +41 -14
- package/build/esm/integrations/pg.js.map +1 -1
- package/build/esm/integrations/pino.js.map +1 -1
- package/build/esm/integrations/tanstack-ai.js +59 -0
- package/build/esm/integrations/tanstack-ai.js.map +1 -0
- package/build/esm/integrations/vercel-ai/extract.js +2 -3
- package/build/esm/integrations/vercel-ai/extract.js.map +1 -1
- package/build/esm/orchestrion/channels.js +2 -0
- package/build/esm/orchestrion/channels.js.map +1 -1
- package/build/esm/orchestrion/config/index.js +2 -0
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/orchestrion/config/prisma.js +2 -0
- package/build/esm/orchestrion/config/prisma.js.map +1 -1
- package/build/esm/orchestrion/config/tanstack-ai.js +19 -0
- package/build/esm/orchestrion/config/tanstack-ai.js.map +1 -0
- package/build/esm/package.json +1 -1
- package/build/esm/tracing-channel.js.map +1 -1
- package/build/types/ai/tanstack-ai/constants.d.ts +8 -0
- package/build/types/ai/tanstack-ai/constants.d.ts.map +1 -0
- package/build/types/ai/tanstack-ai/index.d.ts +18 -0
- package/build/types/ai/tanstack-ai/index.d.ts.map +1 -0
- package/build/types/ai/tanstack-ai/types.d.ts +127 -0
- package/build/types/ai/tanstack-ai/types.d.ts.map +1 -0
- package/build/types/ai/tanstack-ai/utils.d.ts +21 -0
- package/build/types/ai/tanstack-ai/utils.d.ts.map +1 -0
- package/build/types/ai/workers-ai/utils.d.ts.map +1 -1
- package/build/types/index.d.ts +2 -0
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/neon.d.ts.map +1 -1
- package/build/types/integrations/pg.d.ts +6 -1
- package/build/types/integrations/pg.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts.map +1 -1
- package/build/types/integrations/tanstack-ai.d.ts +18 -0
- package/build/types/integrations/tanstack-ai.d.ts.map +1 -0
- package/build/types/integrations/vercel-ai/extract.d.ts +2 -5
- package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +2 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/orchestrion/config/prisma.d.ts +2 -1
- package/build/types/orchestrion/config/prisma.d.ts.map +1 -1
- package/build/types/orchestrion/config/tanstack-ai.d.ts +17 -0
- package/build/types/orchestrion/config/tanstack-ai.d.ts.map +1 -0
- package/build/types/tracing-channel.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// src/ai/tanstack-ai/constants.ts
|
|
2
|
+
const TANSTACK_AI_INTEGRATION_NAME = "TanStackAI";
|
|
3
|
+
const TANSTACK_AI_ORIGIN = "auto.ai.tanstack_ai";
|
|
4
|
+
/**
|
|
5
|
+
* Marks our middleware, so a `chat()` call that already has it does not get a second one.
|
|
6
|
+
* `Symbol.for`, so that two copies of the SDK in one process see each other's middleware.
|
|
7
|
+
*/
|
|
8
|
+
const TANSTACK_AI_MIDDLEWARE_BRAND = Symbol.for("sentry.tanstack-ai.middleware");
|
|
9
|
+
export { TANSTACK_AI_INTEGRATION_NAME, TANSTACK_AI_MIDDLEWARE_BRAND, TANSTACK_AI_ORIGIN };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../../../../src/ai/tanstack-ai/constants.ts"],"sourcesContent":["export const TANSTACK_AI_INTEGRATION_NAME = 'TanStackAI' as const;\n\nexport const TANSTACK_AI_ORIGIN = 'auto.ai.tanstack_ai';\n\n/**\n * Marks our middleware, so a `chat()` call that already has it does not get a second one.\n * `Symbol.for`, so that two copies of the SDK in one process see each other's middleware.\n */\nexport const TANSTACK_AI_MIDDLEWARE_BRAND = Symbol.for('sentry.tanstack-ai.middleware');\n"],"mappings":";AAAA,MAAa,+BAA+B;AAE5C,MAAa,qBAAqB;;;;;AAMlC,MAAa,+BAA+B,OAAO,IAAI,+BAA+B"}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from "../core/gen-ai-attributes.js";
|
|
2
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
3
|
+
import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
|
|
4
|
+
import { getErrorStatus, getGenAiSpanOp, resolveGenAiCallRecording, setOutputMessagesAttribute } from "../core/utils.js";
|
|
5
|
+
import { TANSTACK_AI_MIDDLEWARE_BRAND, TANSTACK_AI_ORIGIN } from "./constants.js";
|
|
6
|
+
import { getInputAttributes, getProviderName, getRequestAttributes, getRunError, getUsageAttributes } from "./utils.js";
|
|
7
|
+
import { GEN_AI_AGENT_NAME, GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DEFINITIONS, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
8
|
+
import { SPAN_STATUS_ERROR, captureException, getActiveSpan, startInactiveSpan, stringify, withActiveSpan } from "@sentry/core";
|
|
9
|
+
// src/ai/tanstack-ai/index.ts
|
|
10
|
+
const OUTPUT_CHUNK_TYPES = /* @__PURE__ */ new Set([
|
|
11
|
+
"TEXT_MESSAGE_CONTENT",
|
|
12
|
+
"TOOL_CALL_START",
|
|
13
|
+
"REASONING_MESSAGE_CONTENT"
|
|
14
|
+
]);
|
|
15
|
+
/**
|
|
16
|
+
* Makes the chat middleware for one `chat()` call. Call it when `chat()` is called: the parent of the
|
|
17
|
+
* `invoke_agent` span is the span that is active then, and the recording options are decided then.
|
|
18
|
+
* The middleware cannot make its spans active, so the spans of other work in the run do not nest
|
|
19
|
+
* below them.
|
|
20
|
+
*/
|
|
21
|
+
function createTanstackAIMiddleware(options, call) {
|
|
22
|
+
const parentSpan = getActiveSpan() ?? null;
|
|
23
|
+
const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
|
|
24
|
+
const streaming = call.outputSchema ? call.stream === true : call.stream !== false;
|
|
25
|
+
let agentSpan;
|
|
26
|
+
let chatSpan;
|
|
27
|
+
let outputText = "";
|
|
28
|
+
let outputToolCalls = [];
|
|
29
|
+
const toolCallNames = /* @__PURE__ */ new Map();
|
|
30
|
+
const toolSpans = /* @__PURE__ */ new Map();
|
|
31
|
+
const startSpan = (spanOptions) => {
|
|
32
|
+
const span = startInactiveSpan(spanOptions);
|
|
33
|
+
runGenAiSpanStart(options, span, call);
|
|
34
|
+
return span;
|
|
35
|
+
};
|
|
36
|
+
const endSpan = (span, status, error) => {
|
|
37
|
+
if (status) span.setStatus(status);
|
|
38
|
+
runGenAiSpanEnd(options, span, call, status ? { error } : {});
|
|
39
|
+
span.end();
|
|
40
|
+
};
|
|
41
|
+
const endChatSpan = (status, error) => {
|
|
42
|
+
if (chatSpan) {
|
|
43
|
+
endSpan(chatSpan, status, error);
|
|
44
|
+
chatSpan = void 0;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const endRun = (status, error) => {
|
|
48
|
+
if (!agentSpan) return;
|
|
49
|
+
for (const span of toolSpans.values()) endSpan(span, status, error);
|
|
50
|
+
toolSpans.clear();
|
|
51
|
+
endChatSpan(status, error);
|
|
52
|
+
endSpan(agentSpan, status, error);
|
|
53
|
+
agentSpan = void 0;
|
|
54
|
+
};
|
|
55
|
+
const startChatSpan = (ctx, config) => {
|
|
56
|
+
outputText = "";
|
|
57
|
+
outputToolCalls = [];
|
|
58
|
+
toolCallNames.clear();
|
|
59
|
+
return startSpan({
|
|
60
|
+
name: `chat ${ctx.model}`,
|
|
61
|
+
op: getGenAiSpanOp("chat"),
|
|
62
|
+
parentSpan: agentSpan,
|
|
63
|
+
attributes: {
|
|
64
|
+
[SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
|
|
65
|
+
[GEN_AI_OPERATION_NAME]: "chat",
|
|
66
|
+
[GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
|
|
67
|
+
[GEN_AI_REQUEST_MODEL]: ctx.model,
|
|
68
|
+
[GEN_AI_CONVERSATION_ID]: ctx.threadId,
|
|
69
|
+
[GEN_AI_RESPONSE_STREAMING]: streaming,
|
|
70
|
+
...getRequestAttributes(config.modelOptions),
|
|
71
|
+
...recordInputs && config.tools.length && ctx.phase !== "structuredOutput" ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(config.tools.map(({ name, description, inputSchema }) => ({
|
|
72
|
+
name,
|
|
73
|
+
description,
|
|
74
|
+
inputSchema
|
|
75
|
+
}))) } : {},
|
|
76
|
+
...recordInputs ? getInputAttributes(config.providerMessages ?? config.messages, config.systemPrompts) : {}
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
name: "sentry",
|
|
82
|
+
[TANSTACK_AI_MIDDLEWARE_BRAND]: true,
|
|
83
|
+
onConfig(ctx, config) {
|
|
84
|
+
if (ctx.phase === "init" && !agentSpan) {
|
|
85
|
+
const agentName = ctx.subagentName;
|
|
86
|
+
agentSpan = startSpan({
|
|
87
|
+
name: agentName ? `invoke_agent ${agentName}` : "invoke_agent",
|
|
88
|
+
op: getGenAiSpanOp("invoke_agent"),
|
|
89
|
+
parentSpan,
|
|
90
|
+
attributes: {
|
|
91
|
+
[SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
|
|
92
|
+
[GEN_AI_OPERATION_NAME]: "invoke_agent",
|
|
93
|
+
[GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
|
|
94
|
+
[GEN_AI_REQUEST_MODEL]: ctx.model,
|
|
95
|
+
[GEN_AI_CONVERSATION_ID]: ctx.threadId,
|
|
96
|
+
[GEN_AI_RESPONSE_STREAMING]: streaming,
|
|
97
|
+
[GEN_AI_AGENT_NAME]: agentName,
|
|
98
|
+
...recordInputs ? getInputAttributes(config.messages, config.systemPrompts) : {}
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (!agentSpan || ctx.phase !== "beforeModel" && ctx.phase !== "structuredOutput") return;
|
|
103
|
+
endChatSpan({
|
|
104
|
+
code: SPAN_STATUS_ERROR,
|
|
105
|
+
message: "internal_error"
|
|
106
|
+
});
|
|
107
|
+
chatSpan = startChatSpan(ctx, config);
|
|
108
|
+
},
|
|
109
|
+
onChunk(ctx, chunk) {
|
|
110
|
+
if (!agentSpan) return;
|
|
111
|
+
if (chunk.type === "RUN_FINISHED" || chunk.type === "RUN_ERROR") {
|
|
112
|
+
const provider = getProviderName(ctx);
|
|
113
|
+
chatSpan?.setAttribute(GEN_AI_PROVIDER_NAME, provider);
|
|
114
|
+
agentSpan.setAttribute(GEN_AI_PROVIDER_NAME, provider);
|
|
115
|
+
}
|
|
116
|
+
if (chunk.type === "RUN_ERROR") {
|
|
117
|
+
endRun(getErrorStatus(ctx.signal), getRunError(chunk));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (chunk.type === "RUN_FINISHED" && chunk.outcome?.type === "interrupt") {
|
|
121
|
+
endRun();
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (!chatSpan) return;
|
|
125
|
+
if (streaming && OUTPUT_CHUNK_TYPES.has(chunk.type)) recordTimeToFirstChunk(chatSpan);
|
|
126
|
+
if (chunk.type === "TEXT_MESSAGE_CONTENT" && recordOutputs && chunk.delta) outputText += chunk.delta;
|
|
127
|
+
else if (chunk.type === "TOOL_CALL_START" && chunk.toolCallId && chunk.toolCallName) toolCallNames.set(chunk.toolCallId, chunk.toolCallName);
|
|
128
|
+
else if (chunk.type === "TOOL_CALL_END" && recordOutputs && chunk.toolCallId) outputToolCalls.push({
|
|
129
|
+
id: chunk.toolCallId,
|
|
130
|
+
name: toolCallNames.get(chunk.toolCallId),
|
|
131
|
+
arguments: chunk.input ?? {}
|
|
132
|
+
});
|
|
133
|
+
else if (chunk.type === "RUN_FINISHED") {
|
|
134
|
+
const responseModel = chunk.model ?? ctx.callMetadata?.model;
|
|
135
|
+
const responseId = chunk.responseId ?? ctx.callMetadata?.responseId;
|
|
136
|
+
const finishReason = chunk.finishReason ?? void 0;
|
|
137
|
+
if (finishReason) chatSpan.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));
|
|
138
|
+
for (const span of [chatSpan, agentSpan]) {
|
|
139
|
+
if (responseModel) span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);
|
|
140
|
+
if (responseId) span.setAttribute(GEN_AI_RESPONSE_ID, responseId);
|
|
141
|
+
if (recordOutputs) setOutputMessagesAttribute(span, {
|
|
142
|
+
responseText: outputText,
|
|
143
|
+
toolCalls: outputToolCalls,
|
|
144
|
+
finishReason
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
onInterruptBoundary(ctx) {
|
|
150
|
+
if (ctx.phase === "afterModel") endChatSpan();
|
|
151
|
+
},
|
|
152
|
+
onUsage(_ctx, usage) {
|
|
153
|
+
chatSpan?.setAttributes(getUsageAttributes(usage));
|
|
154
|
+
},
|
|
155
|
+
onGuardToolCall(ctx, { toolName, toolCallId, args, tool }) {
|
|
156
|
+
if (!agentSpan || tool && typeof tool.execute !== "function") return;
|
|
157
|
+
toolSpans.set(toolCallId, startSpan({
|
|
158
|
+
name: `execute_tool ${toolName}`,
|
|
159
|
+
op: getGenAiSpanOp("execute_tool"),
|
|
160
|
+
parentSpan: agentSpan,
|
|
161
|
+
attributes: {
|
|
162
|
+
[SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
|
|
163
|
+
[GEN_AI_OPERATION_NAME]: "execute_tool",
|
|
164
|
+
[GEN_AI_TOOL_NAME]: toolName,
|
|
165
|
+
[GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,
|
|
166
|
+
[GEN_AI_CONVERSATION_ID]: ctx.threadId,
|
|
167
|
+
[GEN_AI_TOOL_DESCRIPTION]: tool?.description,
|
|
168
|
+
...recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}
|
|
169
|
+
}
|
|
170
|
+
}));
|
|
171
|
+
},
|
|
172
|
+
onAfterToolCall(ctx, { toolCallId, ok, result, error }) {
|
|
173
|
+
const span = toolSpans.get(toolCallId);
|
|
174
|
+
if (!span) return;
|
|
175
|
+
toolSpans.delete(toolCallId);
|
|
176
|
+
if (recordOutputs && ok && result !== void 0) span.setAttribute(GEN_AI_TOOL_CALL_RESULT, typeof result === "string" ? result : stringify(result));
|
|
177
|
+
if (ok) {
|
|
178
|
+
endSpan(span);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
const status = getErrorStatus(ctx.signal);
|
|
182
|
+
if (status.message === "internal_error") withActiveSpan(span, () => {
|
|
183
|
+
captureException(error, { mechanism: {
|
|
184
|
+
type: TANSTACK_AI_ORIGIN,
|
|
185
|
+
handled: false
|
|
186
|
+
} });
|
|
187
|
+
});
|
|
188
|
+
endSpan(span, status, error);
|
|
189
|
+
},
|
|
190
|
+
onFinish() {
|
|
191
|
+
endRun();
|
|
192
|
+
},
|
|
193
|
+
onAbort() {
|
|
194
|
+
endRun({
|
|
195
|
+
code: SPAN_STATUS_ERROR,
|
|
196
|
+
message: "cancelled"
|
|
197
|
+
});
|
|
198
|
+
},
|
|
199
|
+
onError(ctx, { error }) {
|
|
200
|
+
endRun(getErrorStatus(ctx.signal), error);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
export { createTanstackAIMiddleware };
|
|
205
|
+
|
|
206
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/tanstack-ai/index.ts"],"sourcesContent":["import type { Span, SpanStatus } from '@sentry/core';\nimport {\n captureException,\n getActiveSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringify,\n withActiveSpan,\n} from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getErrorStatus, getGenAiSpanOp, resolveGenAiCallRecording, setOutputMessagesAttribute } from '../core/utils';\nimport { TANSTACK_AI_MIDDLEWARE_BRAND, TANSTACK_AI_ORIGIN } from './constants';\nimport type {\n TanstackAICallInfo,\n TanstackAIChatMiddleware,\n TanstackAIMiddlewareConfig,\n TanstackAIMiddlewareContext,\n} from './types';\nimport { getInputAttributes, getProviderName, getRequestAttributes, getRunError, getUsageAttributes } from './utils';\n\n/**\n * `call` is the options object of the `chat()` call. The recording options run when `chat()` is\n * called. The hooks run for every span (`invoke_agent`, `chat` and `execute_tool`) while the run is\n * read, which can be in another async context than the call. `onSpanEnd` gets the `error` of a\n * failed run or tool.\n */\nexport type TanstackAIOptions = GenAiCallOptions<TanstackAICallInfo> & GenAiSpanHooks<TanstackAICallInfo>;\n\n// The chunks that carry model output. The adapters send `RUN_STARTED` before the provider answers.\nconst OUTPUT_CHUNK_TYPES = new Set(['TEXT_MESSAGE_CONTENT', 'TOOL_CALL_START', 'REASONING_MESSAGE_CONTENT']);\n\n/**\n * Makes the chat middleware for one `chat()` call. Call it when `chat()` is called: the parent of the\n * `invoke_agent` span is the span that is active then, and the recording options are decided then.\n * The middleware cannot make its spans active, so the spans of other work in the run do not nest\n * below them.\n */\nexport function createTanstackAIMiddleware(\n options: TanstackAIOptions,\n call: TanstackAICallInfo,\n): TanstackAIChatMiddleware {\n const parentSpan = getActiveSpan() ?? null;\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n // `ctx.streaming` is also true when `chat()` returns a promise, because `chat()` reads the same stream\n // inside. With `outputSchema`, `chat()` streams only with `stream: true`.\n const streaming = call.outputSchema ? call.stream === true : call.stream !== false;\n\n let agentSpan: Span | undefined;\n let chatSpan: Span | undefined;\n let outputText = '';\n let outputToolCalls: Array<{ id: string; name?: string; arguments: unknown }> = [];\n // `TOOL_CALL_END` has the arguments but not the name, which only `TOOL_CALL_START` has.\n const toolCallNames = new Map<string, string>();\n const toolSpans = new Map<string, Span>();\n\n const startSpan = (spanOptions: Parameters<typeof startInactiveSpan>[0]): Span => {\n const span = startInactiveSpan(spanOptions);\n runGenAiSpanStart(options, span, call);\n return span;\n };\n\n const endSpan = (span: Span, status?: SpanStatus, error?: unknown): void => {\n if (status) {\n span.setStatus(status);\n }\n runGenAiSpanEnd(options, span, call, status ? { error } : {});\n span.end();\n };\n\n const endChatSpan = (status?: SpanStatus, error?: unknown): void => {\n if (chatSpan) {\n endSpan(chatSpan, status, error);\n chatSpan = undefined;\n }\n };\n\n const endRun = (status?: SpanStatus, error?: unknown): void => {\n if (!agentSpan) {\n return;\n }\n for (const span of toolSpans.values()) {\n endSpan(span, status, error);\n }\n toolSpans.clear();\n endChatSpan(status, error);\n endSpan(agentSpan, status, error);\n agentSpan = undefined;\n };\n\n const startChatSpan = (ctx: TanstackAIMiddlewareContext, config: TanstackAIMiddlewareConfig): Span => {\n outputText = '';\n outputToolCalls = [];\n toolCallNames.clear();\n\n return startSpan({\n name: `chat ${ctx.model}`,\n op: getGenAiSpanOp('chat'),\n parentSpan: agentSpan,\n attributes: {\n [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'chat',\n [GEN_AI_PROVIDER_NAME]: getProviderName(ctx),\n [GEN_AI_REQUEST_MODEL]: ctx.model,\n [GEN_AI_CONVERSATION_ID]: ctx.threadId,\n [GEN_AI_RESPONSE_STREAMING]: streaming,\n ...getRequestAttributes(config.modelOptions),\n // The `structuredOutput` call sends no tools, but its config still lists them.\n ...(recordInputs && config.tools.length && ctx.phase !== 'structuredOutput'\n ? {\n [GEN_AI_TOOL_DEFINITIONS]: stringify(\n config.tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),\n ),\n }\n : {}),\n // A middleware can send the provider other messages than the history of the run.\n ...(recordInputs ? getInputAttributes(config.providerMessages ?? config.messages, config.systemPrompts) : {}),\n },\n });\n };\n\n return {\n name: 'sentry',\n [TANSTACK_AI_MIDDLEWARE_BRAND]: true,\n\n onConfig(ctx, config) {\n // `init` runs once per run, before `onStart` and before any tool can run.\n if (ctx.phase === 'init' && !agentSpan) {\n const agentName = ctx.subagentName;\n agentSpan = startSpan({\n name: agentName ? `invoke_agent ${agentName}` : 'invoke_agent',\n op: getGenAiSpanOp('invoke_agent'),\n parentSpan,\n attributes: {\n [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_PROVIDER_NAME]: getProviderName(ctx),\n [GEN_AI_REQUEST_MODEL]: ctx.model,\n [GEN_AI_CONVERSATION_ID]: ctx.threadId,\n [GEN_AI_RESPONSE_STREAMING]: streaming,\n [GEN_AI_AGENT_NAME]: agentName,\n ...(recordInputs ? getInputAttributes(config.messages, config.systemPrompts) : {}),\n },\n });\n }\n\n // `beforeModel` starts each model call of the agent loop. `structuredOutput` starts the\n // separate last call for `outputSchema`.\n if (!agentSpan || (ctx.phase !== 'beforeModel' && ctx.phase !== 'structuredOutput')) {\n return;\n }\n // A model call that completes ends its span at the `afterModel` boundary. A span that is still\n // open here is of a call that failed and that a middleware retried with `ctx.retry()`.\n endChatSpan({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n chatSpan = startChatSpan(ctx, config);\n },\n\n onChunk(ctx, chunk) {\n if (!agentSpan) {\n return;\n }\n if (chunk.type === 'RUN_FINISHED' || chunk.type === 'RUN_ERROR') {\n // TanStack sets the call metadata of the `structuredOutput` call only after `onConfig`.\n const provider = getProviderName(ctx);\n chatSpan?.setAttribute(GEN_AI_PROVIDER_NAME, provider);\n agentSpan.setAttribute(GEN_AI_PROVIDER_NAME, provider);\n }\n // A provider error ends the run with this chunk. `chat({ stream: false })` then throws and\n // stops reading, so TanStack calls no terminal hook.\n if (chunk.type === 'RUN_ERROR') {\n endRun(getErrorStatus(ctx.signal), getRunError(chunk));\n return;\n }\n // A run that stops at an interrupt ends with this chunk. For an interrupt at `beforeModel` or\n // `afterModel`, TanStack calls no terminal hook.\n if (chunk.type === 'RUN_FINISHED' && chunk.outcome?.type === 'interrupt') {\n endRun();\n return;\n }\n if (!chatSpan) {\n return;\n }\n\n if (streaming && OUTPUT_CHUNK_TYPES.has(chunk.type)) {\n recordTimeToFirstChunk(chatSpan);\n }\n\n if (chunk.type === 'TEXT_MESSAGE_CONTENT' && recordOutputs && chunk.delta) {\n outputText += chunk.delta;\n } else if (chunk.type === 'TOOL_CALL_START' && chunk.toolCallId && chunk.toolCallName) {\n toolCallNames.set(chunk.toolCallId, chunk.toolCallName);\n } else if (chunk.type === 'TOOL_CALL_END' && recordOutputs && chunk.toolCallId) {\n outputToolCalls.push({\n id: chunk.toolCallId,\n name: toolCallNames.get(chunk.toolCallId),\n arguments: chunk.input ?? {},\n });\n } else if (chunk.type === 'RUN_FINISHED') {\n // An adapter can report these only in the `metadata.tanstack` of the chunk. TanStack copies\n // them into `callMetadata` before the middleware gets the chunk.\n const responseModel = chunk.model ?? ctx.callMetadata?.model;\n const responseId = chunk.responseId ?? ctx.callMetadata?.responseId;\n const finishReason = chunk.finishReason ?? undefined;\n if (finishReason) {\n chatSpan.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));\n }\n // The agent span keeps the response of the last model call, which is the answer of the run.\n for (const span of [chatSpan, agentSpan]) {\n if (responseModel) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);\n }\n if (responseId) {\n span.setAttribute(GEN_AI_RESPONSE_ID, responseId);\n }\n if (recordOutputs) {\n setOutputMessagesAttribute(span, { responseText: outputText, toolCalls: outputToolCalls, finishReason });\n }\n }\n }\n },\n\n // Runs after each model call and before the tools it asked for, so the `chat` span does not\n // include the tools.\n onInterruptBoundary(ctx) {\n if (ctx.phase === 'afterModel') {\n endChatSpan();\n }\n },\n\n onUsage(_ctx, usage) {\n chatSpan?.setAttributes(getUsageAttributes(usage));\n },\n\n // The guards run after all `onBeforeToolCall` decisions and after the input check, so `args`\n // are the arguments that the tool gets.\n onGuardToolCall(ctx, { toolName, toolCallId, args, tool }) {\n // A client tool runs in the browser, not here.\n if (!agentSpan || (tool && typeof tool.execute !== 'function')) {\n return;\n }\n toolSpans.set(\n toolCallId,\n startSpan({\n name: `execute_tool ${toolName}`,\n op: getGenAiSpanOp('execute_tool'),\n parentSpan: agentSpan,\n attributes: {\n [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_CONVERSATION_ID]: ctx.threadId,\n [GEN_AI_TOOL_DESCRIPTION]: tool?.description,\n ...(recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n }),\n );\n },\n\n onAfterToolCall(ctx, { toolCallId, ok, result, error }) {\n const span = toolSpans.get(toolCallId);\n if (!span) {\n return;\n }\n toolSpans.delete(toolCallId);\n\n if (recordOutputs && ok && result !== undefined) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, typeof result === 'string' ? result : stringify(result));\n }\n if (ok) {\n endSpan(span);\n return;\n }\n // TanStack fails each tool that did not start yet with an `Operation aborted` error.\n const status = getErrorStatus(ctx.signal);\n if (status.message === 'internal_error') {\n // TanStack gives a tool failure back to the model as the tool result, so the error handlers\n // of the app never see it.\n withActiveSpan(span, () => {\n captureException(error, { mechanism: { type: TANSTACK_AI_ORIGIN, handled: false } });\n });\n }\n endSpan(span, status, error);\n },\n\n onFinish() {\n endRun();\n },\n\n // Also for an abort from a middleware, which leaves the signal of the caller alone.\n onAbort() {\n endRun({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n },\n\n onError(ctx, { error }) {\n endRun(getErrorStatus(ctx.signal), error);\n },\n };\n}\n"],"mappings":";;;;;;;;;AAkDA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAwB;CAAmB;AAA2B,CAAC;;;;;;;AAQ3G,SAAgB,2BACd,SACA,MAC0B;CAC1B,MAAM,aAAa,cAAc,KAAK;CACtC,MAAM,EAAE,cAAc,kBAAkB,0BAA0B,SAAS,IAAI;CAG/E,MAAM,YAAY,KAAK,eAAe,KAAK,WAAW,OAAO,KAAK,WAAW;CAE7E,IAAI;CACJ,IAAI;CACJ,IAAI,aAAa;CACjB,IAAI,kBAA4E,CAAC;CAEjF,MAAM,gCAAgB,IAAI,IAAoB;CAC9C,MAAM,4BAAY,IAAI,IAAkB;CAExC,MAAM,aAAa,gBAA+D;EAChF,MAAM,OAAO,kBAAkB,WAAW;EAC1C,kBAAkB,SAAS,MAAM,IAAI;EACrC,OAAO;CACT;CAEA,MAAM,WAAW,MAAY,QAAqB,UAA0B;EAC1E,IAAI,QACF,KAAK,UAAU,MAAM;EAEvB,gBAAgB,SAAS,MAAM,MAAM,SAAS,EAAE,MAAM,IAAI,CAAC,CAAC;EAC5D,KAAK,IAAI;CACX;CAEA,MAAM,eAAe,QAAqB,UAA0B;EAClE,IAAI,UAAU;GACZ,QAAQ,UAAU,QAAQ,KAAK;GAC/B,WAAW,KAAA;EACb;CACF;CAEA,MAAM,UAAU,QAAqB,UAA0B;EAC7D,IAAI,CAAC,WACH;EAEF,KAAK,MAAM,QAAQ,UAAU,OAAO,GAClC,QAAQ,MAAM,QAAQ,KAAK;EAE7B,UAAU,MAAM;EAChB,YAAY,QAAQ,KAAK;EACzB,QAAQ,WAAW,QAAQ,KAAK;EAChC,YAAY,KAAA;CACd;CAEA,MAAM,iBAAiB,KAAkC,WAA6C;EAC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AI_INPUT_MESSAGES, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_P, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS } from "@sentry/conventions/attributes";
|
|
3
|
+
import { stringify } from "@sentry/core";
|
|
4
|
+
// src/ai/tanstack-ai/utils.ts
|
|
5
|
+
/**
|
|
6
|
+
* `ctx.provider` is the adapter name, which for some adapters also names the API (for example
|
|
7
|
+
* `openrouter-responses`). The call metadata has the provider of the adapter, but only after the
|
|
8
|
+
* first model call started.
|
|
9
|
+
*/
|
|
10
|
+
function getProviderName(ctx) {
|
|
11
|
+
return ctx.callMetadata?.source?.provider ?? ctx.provider;
|
|
12
|
+
}
|
|
13
|
+
function getInputAttributes(messages, systemPrompts) {
|
|
14
|
+
return {
|
|
15
|
+
[GEN_AI_INPUT_MESSAGES]: stringify(messages.map(toGenAiMessage)),
|
|
16
|
+
[GEN_AI_SYSTEM_INSTRUCTIONS]: systemPrompts.length ? stringify(systemPrompts.map((prompt) => ({
|
|
17
|
+
type: "text",
|
|
18
|
+
content: typeof prompt === "string" ? prompt : prompt.content
|
|
19
|
+
}))) : void 0
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* TanStack AI has no common option for temperature, top p or max tokens. Each adapter takes them in
|
|
24
|
+
* `modelOptions` and passes them to the provider with the provider's key name (snake_case or camelCase,
|
|
25
|
+
* and `max_tokens` or `max_output_tokens`). So we take the first of the known keys that has a value.
|
|
26
|
+
*/
|
|
27
|
+
function getRequestAttributes(modelOptions = {}) {
|
|
28
|
+
const pick = (...keys) => {
|
|
29
|
+
for (const key of keys) {
|
|
30
|
+
const value = modelOptions[key];
|
|
31
|
+
if (typeof value === "number") return value;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
[GEN_AI_REQUEST_TEMPERATURE]: pick("temperature"),
|
|
36
|
+
[GEN_AI_REQUEST_TOP_P]: pick("top_p", "topP"),
|
|
37
|
+
[GEN_AI_REQUEST_MAX_TOKENS]: pick("max_tokens", "maxTokens", "max_output_tokens", "maxOutputTokens")
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function getUsageAttributes(usage) {
|
|
41
|
+
const attributes = getTokenUsageAttributes(usage.promptTokens, usage.completionTokens, usage.promptTokensDetails?.cacheWriteTokens, usage.promptTokensDetails?.cachedTokens, usage.totalTokens);
|
|
42
|
+
if (typeof usage.completionTokensDetails?.reasoningTokens === "number") attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = usage.completionTokensDetails.reasoningTokens;
|
|
43
|
+
return attributes;
|
|
44
|
+
}
|
|
45
|
+
function toGenAiMessage(message) {
|
|
46
|
+
const parts = [];
|
|
47
|
+
const { content } = message;
|
|
48
|
+
if (message.role === "tool") parts.push({
|
|
49
|
+
type: "tool_call_response",
|
|
50
|
+
id: message.toolCallId,
|
|
51
|
+
result: content
|
|
52
|
+
});
|
|
53
|
+
else if (typeof content === "string") parts.push({
|
|
54
|
+
type: "text",
|
|
55
|
+
content
|
|
56
|
+
});
|
|
57
|
+
else if (Array.isArray(content)) for (const part of content) parts.push(part.type === "text" ? {
|
|
58
|
+
type: "text",
|
|
59
|
+
content: part.content
|
|
60
|
+
} : { type: part.type });
|
|
61
|
+
for (const toolCall of message.toolCalls ?? []) parts.push({
|
|
62
|
+
type: "tool_call",
|
|
63
|
+
id: toolCall.id,
|
|
64
|
+
name: toolCall.function?.name,
|
|
65
|
+
arguments: toolCall.function?.arguments
|
|
66
|
+
});
|
|
67
|
+
return {
|
|
68
|
+
role: message.role,
|
|
69
|
+
parts
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** The error of a `RUN_ERROR` chunk. */
|
|
73
|
+
function getRunError(chunk) {
|
|
74
|
+
return chunk.error ?? {
|
|
75
|
+
message: chunk.message,
|
|
76
|
+
code: chunk.code
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
export { getInputAttributes, getProviderName, getRequestAttributes, getRunError, getUsageAttributes };
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/tanstack-ai/utils.ts"],"sourcesContent":["import { stringify } from '@sentry/core';\nimport {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { getTokenUsageAttributes } from '../core/utils';\nimport type {\n TanstackAIChunk,\n TanstackAIMiddlewareContext,\n TanstackAIModelMessage,\n TanstackAISystemPrompt,\n TanstackAIUsage,\n} from './types';\n\n/**\n * `ctx.provider` is the adapter name, which for some adapters also names the API (for example\n * `openrouter-responses`). The call metadata has the provider of the adapter, but only after the\n * first model call started.\n */\nexport function getProviderName(ctx: TanstackAIMiddlewareContext): string {\n return ctx.callMetadata?.source?.provider ?? ctx.provider;\n}\n\nexport function getInputAttributes(\n messages: ReadonlyArray<TanstackAIModelMessage>,\n systemPrompts: ReadonlyArray<TanstackAISystemPrompt>,\n): Record<string, string | undefined> {\n return {\n [GEN_AI_INPUT_MESSAGES]: stringify(messages.map(toGenAiMessage)),\n [GEN_AI_SYSTEM_INSTRUCTIONS]: systemPrompts.length\n ? stringify(\n systemPrompts.map(prompt => ({\n type: 'text',\n content: typeof prompt === 'string' ? prompt : prompt.content,\n })),\n )\n : undefined,\n };\n}\n\n/**\n * TanStack AI has no common option for temperature, top p or max tokens. Each adapter takes them in\n * `modelOptions` and passes them to the provider with the provider's key name (snake_case or camelCase,\n * and `max_tokens` or `max_output_tokens`). So we take the first of the known keys that has a value.\n */\nexport function getRequestAttributes(modelOptions: Record<string, unknown> = {}): Record<string, number | undefined> {\n const pick = (...keys: string[]): number | undefined => {\n for (const key of keys) {\n const value = modelOptions[key];\n if (typeof value === 'number') {\n return value;\n }\n }\n return undefined;\n };\n return {\n [GEN_AI_REQUEST_TEMPERATURE]: pick('temperature'),\n [GEN_AI_REQUEST_TOP_P]: pick('top_p', 'topP'),\n [GEN_AI_REQUEST_MAX_TOKENS]: pick('max_tokens', 'maxTokens', 'max_output_tokens', 'maxOutputTokens'),\n };\n}\n\nexport function getUsageAttributes(usage: TanstackAIUsage): Record<string, number> {\n const attributes = getTokenUsageAttributes(\n usage.promptTokens,\n usage.completionTokens,\n usage.promptTokensDetails?.cacheWriteTokens,\n usage.promptTokensDetails?.cachedTokens,\n usage.totalTokens,\n );\n if (typeof usage.completionTokensDetails?.reasoningTokens === 'number') {\n attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = usage.completionTokensDetails.reasoningTokens;\n }\n return attributes;\n}\n\nfunction toGenAiMessage(message: TanstackAIModelMessage): Record<string, unknown> {\n const parts: Array<Record<string, unknown>> = [];\n const { content } = message;\n\n if (message.role === 'tool') {\n parts.push({ type: 'tool_call_response', id: message.toolCallId, result: content });\n } else if (typeof content === 'string') {\n parts.push({ type: 'text', content });\n } else if (Array.isArray(content)) {\n for (const part of content) {\n // Media parts carry inline data or provider handles, so keep only their type.\n parts.push(part.type === 'text' ? { type: 'text', content: part.content } : { type: part.type });\n }\n }\n for (const toolCall of message.toolCalls ?? []) {\n parts.push({\n type: 'tool_call',\n id: toolCall.id,\n name: toolCall.function?.name,\n arguments: toolCall.function?.arguments,\n });\n }\n return { role: message.role, parts };\n}\n\n/** The error of a `RUN_ERROR` chunk. */\nexport function getRunError(chunk: TanstackAIChunk): { message?: string; code?: string } {\n return chunk.error ?? { message: chunk.message, code: chunk.code };\n}\n"],"mappings":";;;;;;;;;AAuBA,SAAgB,gBAAgB,KAA0C;CACxE,OAAO,IAAI,cAAc,QAAQ,YAAY,IAAI;AACnD;AAEA,SAA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AC,GAC3C,MAAM,KAAK;EACT,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS,UAAU;EACzB,WAAW,SAAS,UAAU;CAChC,CAAC;CAEH,OAAO;EAAE,MAAM,QAAQ;EAAM;CAAM;AACrC;;AAGA,SAAgB,YAAY,OAA6D;CACvF,OAAO,MAAM,SAAS;EAAE,SAAS,MAAM;EAAS,MAAM,MAAM;CAAK;AACnE"}
|
|
@@ -69,7 +69,10 @@ function addRequestAttributes(span, inputs, operationName) {
|
|
|
69
69
|
}
|
|
70
70
|
if (operationName === "extract") {
|
|
71
71
|
const { model: _model, ...request } = inputs;
|
|
72
|
-
|
|
72
|
+
for (const key of ["images", "documents"]) {
|
|
73
|
+
const blobs = request[key];
|
|
74
|
+
if (Array.isArray(blobs)) request[key] = blobs.map(() => BLOB_SUBSTITUTE);
|
|
75
|
+
}
|
|
73
76
|
span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));
|
|
74
77
|
return;
|
|
75
78
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["addDecideResponseAttributes"],"sources":["../../../../src/ai/workers-ai/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EMBEDDINGS, GEN_AI_DECIDE, GEN_AI_EXTRACT } from '@sentry/conventions/op';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport {\n extractSystemInstructions,\n getEvaluationInputMessages,\n getTokenUsageAttributes,\n setOutputMessagesAttribute,\n} from '../core/utils';\nimport { addResponseAttributes as addDecideResponseAttributes } from '../typesafe';\n// Re-exported so `workers-ai/streaming.ts` keeps importing it from this module.\nexport { setOutputMessagesAttribute };\nimport { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants';\nimport type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types';\n\nexport type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract';\n\nexport const WORKERS_AI_OPERATION_SPAN_OPS: Record<WorkersAiOperationName, string> = {\n chat: GEN_AI_CHAT,\n embeddings: GEN_AI_EMBEDDINGS,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n};\n\n/**\n * Model ID prefixes of the evaluation models (TypeSafe Jev and Cloudflare Clef), traced as `decide` spans.\n */\nconst DECIDE_MODEL_PREFIXES = ['typesafe/jev', '@cf/cloudflare/clef'];\n\n/**\n * Model ID prefixes of the field extraction models (Cloudflare Clairic), traced as `extract` spans.\n */\nconst EXTRACT_MODEL_PREFIXES = ['@cf/cloudflare/clairic'];\n\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\n/**\n * Determine the gen_ai operation name from the model and inputs passed to `AI.run`.\n * Workers AI exposes a single `run` method, so we infer the operation from the model ID and the input shape.\n */\nexport function getOperationName(model: unknown, inputs: unknown): WorkersAiOperationName {\n if (typeof model === 'string' && DECIDE_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'decide';\n }\n if (typeof model === 'string' && EXTRACT_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'extract';\n }\n if (inputs && typeof inputs === 'object') {\n if ('messages' in inputs || 'prompt' in inputs) {\n return 'chat';\n }\n if ('text' in inputs) {\n return 'embeddings';\n }\n }\n return 'chat';\n}\n\n/**\n * Extract the request attributes (model, request parameters, system, origin) from a `run` call.\n */\nexport function extractRequestAttributes(\n model: unknown,\n inputs: unknown,\n operationName: string,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: WORKERS_AI_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: WORKERS_AI_ORIGIN,\n [GEN_AI_REQUEST_MODEL]: typeof model === 'string' ? model : 'unknown',\n };\n\n if (inputs && typeof inputs === 'object') {\n const params = inputs as WorkersAiInput;\n\n if (typeof params.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n }\n if (typeof params.max_tokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n if (typeof params.top_p === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n }\n if (typeof params.top_k === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n }\n if (typeof params.frequency_penalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n }\n if (typeof params.presence_penalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n }\n if (params.stream === true) {\n attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = true;\n }\n }\n\n return attributes;\n}\n\n/**\n * Record the request inputs (messages/prompt/embeddings input) on the span.\n * Only called when `recordInputs` is enabled.\n */\nexport function addRequestAttributes(span: Span, inputs: unknown, operationName: string): void {\n if (!inputs || typeof inputs !== 'object') {\n return;\n }\n const params = inputs as WorkersAiInput;\n\n if (operationName === 'decide') {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(inputs as Record<string, unknown>));\n return;\n }\n\n if (operationName === 'extract') {\n // Record the request body as passed, but never the image data.\n const { model: _model, ...request } = inputs as Record<string, unknown>;\n if (Array.isArray(request.images)) {\n request.images = request.images.map(() => BLOB_SUBSTITUTE);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings') {\n const text = params.text;\n\n if (text == null || (typeof text === 'string' && text.length === 0) || (Array.isArray(text) && text.length === 0)) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(text, String));\n return;\n }\n\n const src = params.messages ?? params.prompt;\n\n if (src == null || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Record the response attributes (token usage, response text, tool calls) on the span.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs: boolean,\n operationName?: WorkersAiOperationName,\n): void {\n if (operationName === 'decide') {\n // The binding wraps the TypeSafe response as `{ state, result }`, but the docs show it unwrapped.\n const body = isObjectLike(result) && isObjectLike(result.result) ? result.result : result;\n addDecideResponseAttributes(span, body, recordOutputs);\n return;\n }\n\n if (operationName === 'extract') {\n addExtractResponseAttributes(span, result, recordOutputs);\n return;\n }\n\n if (\n !result ||\n typeof result !== 'object' ||\n // Raw `Response` objects (from `returnRawResponse`/`websocket`) cannot be introspected without consuming them.\n (typeof Response !== 'undefined' && result instanceof Response)\n ) {\n return;\n }\n\n const response = result as WorkersAiOutput;\n\n if (response.usage) {\n span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));\n }\n\n if (Array.isArray(response.choices)) {\n if (typeof response.id === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_ID, response.id);\n }\n if (typeof response.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model);\n }\n addChoicesResponseAttributes(span, response.choices, recordOutputs);\n return;\n }\n\n if (recordOutputs) {\n let responseText: string | undefined;\n if (typeof response.response === 'string') {\n responseText = response.response;\n span.setAttribute(GEN_AI_RESPONSE_TEXT, response.response);\n } else if (response.response != null) {\n responseText = JSON.stringify(response.response);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, responseText);\n }\n\n const toolCalls =\n Array.isArray(response.tool_calls) && response.tool_calls.length > 0 ? response.tool_calls : undefined;\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n setOutputMessagesAttribute(span, { responseText, toolCalls });\n }\n}\n\nfunction addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void {\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons));\n }\n\n if (!recordOutputs) {\n return;\n }\n\n const messages = choices.map(({ message, finish_reason }) => ({\n responseText: typeof message?.content === 'string' ? message.content : undefined,\n toolCalls: message?.tool_calls,\n finishReason: typeof finish_reason === 'string' ? finish_reason : undefined,\n }));\n\n setOutputMessagesAttribute(span, messages);\n}\n\nfunction addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(body)) {\n return;\n }\n\n const { model, usage, ...response } = body;\n\n if (typeof model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, model);\n }\n\n if (isObjectLike(usage)) {\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.input_tokens === 'number' ? usage.input_tokens : undefined,\n typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined,\n ),\n );\n }\n\n if (recordOutputs) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([response]));\n }\n}\n"],"mappings":";;;;;;;;AAwCA,MAAa,gCAAwE;CACnF,MAAM;CACN,YAAY;CACZ,QAAQ;CACR,SAAS;AACX;;;;AAKA,MAAM,wBAAwB,CAAC,gBAAgB,qBAAqB;;;;AAKpE,MAAM,yBAAyB,CAAC,wBAAwB;AAExD,MAAM,kBAAkB;;;;;AAMxB,SAAgB,iBAAiB,OAAgB,QAAyC;CACxF,IAAI,OAAO,UAAU,YAAY,sBAAsB,MAAK,WAAU,MAAM,WAAW,MAAM,CAAC,GAC5F,OAAO;CAET,IAAI,OAAO,UAAU,YAAY,uBAAuB,MAAK,WAAU,MAAM,WAAW,MAAM,CAAC,GAC7F,OAAO;CAET,IAAI,UAAU,OAAO,WAAW,UAAU;EACxC,IAAI,cAAc,UAAU,YAAY,QACtC,OAAO;EAET,IAAI,UAAU,QACZ,OAAO;CAEX;CACA,OAAO;AACT;;;;AAKA,SAAgB,yBACd,OACA,QACA,eACoC;CACpC,MAAM,aAAiD;GACpD,uBAAuB;GACvB,wBAAwB;GACxB,gBAAgB;GAChB,uBAAuB,OAAO,UAAU,WAAW,QAAQ;CAC9D;CAEA,IAAI,UAAU,OAAO,WAAW,UAAU;EACxC,MAAM,SAAS;EAEf,IAAI,OAAO,OAAO,gBAAgB,UAChC,WAAW,8BAA8B,OAAO;EAElD,IAAI,OAAO,OAAO,eAAe,UAC/B,WAAW,6BAA6B,OAAO;EAEjD,IAAI,OAAO,OAAO,UAAU,UAC1B,WAAW,wBAAwB,OAAO;EAE5C,IAAI,OAAO,OAAO,UAAU,UAC1B,WAAW,wBAAwB,OAAO;EAE5C,IAAI,OAAO,OAAO,sBAAsB,UACtC,WAAW,oCAAoC,OAAO;EAExD,IAAI,OAAO,OAAO,qBAAqB,UACrC,WAAW,mCAA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pB,cAAc,OAAO,kBAAkB,WAAW,gBAAgB,KAAA;CACpE,EAAE;CAEF,2BAA2B,MAAM,QAAQ;AAC3C;AAEA,SAAS,6BAA6B,MAAY,MAAe,eAA8B;CAC7F,IAAI,CAAC,aAAa,IAAI,GACpB;CAGF,MAAM,EAAE,OAAO,OAAO,GAAG,aAAa;CAEtC,IAAI,OAAO,UAAU,UACnB,KAAK,aAAa,uBAAuB,KAAK;CAGhD,IAAI,aAAa,KAAK,GACpB,KAAK,cACH,wBACE,OAAO,MAAM,iBAAiB,WAAW,MAAM,eAAe,KAAA,GAC9D,OAAO,MAAM,kBAAkB,WAAW,MAAM,gBAAgB,KAAA,CAClE,CACF;CAGF,IAAI,eACF,KAAK,aAAa,wBAAwB,UAAU,CAAC,QAAQ,CAAC,CAAC;AAEnE"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["addDecideResponseAttributes"],"sources":["../../../../src/ai/workers-ai/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EMBEDDINGS, GEN_AI_DECIDE, GEN_AI_EXTRACT } from '@sentry/conventions/op';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport {\n extractSystemInstructions,\n getEvaluationInputMessages,\n getTokenUsageAttributes,\n setOutputMessagesAttribute,\n} from '../core/utils';\nimport { addResponseAttributes as addDecideResponseAttributes } from '../typesafe';\n// Re-exported so `workers-ai/streaming.ts` keeps importing it from this module.\nexport { setOutputMessagesAttribute };\nimport { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants';\nimport type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types';\n\nexport type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract';\n\nexport const WORKERS_AI_OPERATION_SPAN_OPS: Record<WorkersAiOperationName, string> = {\n chat: GEN_AI_CHAT,\n embeddings: GEN_AI_EMBEDDINGS,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n};\n\n/**\n * Model ID prefixes of the evaluation models (TypeSafe Jev and Cloudflare Clef), traced as `decide` spans.\n */\nconst DECIDE_MODEL_PREFIXES = ['typesafe/jev', '@cf/cloudflare/clef'];\n\n/**\n * Model ID prefixes of the field extraction models (Cloudflare Clairic), traced as `extract` spans.\n */\nconst EXTRACT_MODEL_PREFIXES = ['@cf/cloudflare/clairic'];\n\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\n/**\n * Determine the gen_ai operation name from the model and inputs passed to `AI.run`.\n * Workers AI exposes a single `run` method, so we infer the operation from the model ID and the input shape.\n */\nexport function getOperationName(model: unknown, inputs: unknown): WorkersAiOperationName {\n if (typeof model === 'string' && DECIDE_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'decide';\n }\n if (typeof model === 'string' && EXTRACT_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'extract';\n }\n if (inputs && typeof inputs === 'object') {\n if ('messages' in inputs || 'prompt' in inputs) {\n return 'chat';\n }\n if ('text' in inputs) {\n return 'embeddings';\n }\n }\n return 'chat';\n}\n\n/**\n * Extract the request attributes (model, request parameters, system, origin) from a `run` call.\n */\nexport function extractRequestAttributes(\n model: unknown,\n inputs: unknown,\n operationName: string,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: WORKERS_AI_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: WORKERS_AI_ORIGIN,\n [GEN_AI_REQUEST_MODEL]: typeof model === 'string' ? model : 'unknown',\n };\n\n if (inputs && typeof inputs === 'object') {\n const params = inputs as WorkersAiInput;\n\n if (typeof params.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n }\n if (typeof params.max_tokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n if (typeof params.top_p === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n }\n if (typeof params.top_k === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n }\n if (typeof params.frequency_penalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n }\n if (typeof params.presence_penalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n }\n if (params.stream === true) {\n attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = true;\n }\n }\n\n return attributes;\n}\n\n/**\n * Record the request inputs (messages/prompt/embeddings input) on the span.\n * Only called when `recordInputs` is enabled.\n */\nexport function addRequestAttributes(span: Span, inputs: unknown, operationName: string): void {\n if (!inputs || typeof inputs !== 'object') {\n return;\n }\n const params = inputs as WorkersAiInput;\n\n if (operationName === 'decide') {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(inputs as Record<string, unknown>));\n return;\n }\n\n if (operationName === 'extract') {\n // Record the request body as passed, but never the image or document data.\n const { model: _model, ...request } = inputs as Record<string, unknown>;\n for (const key of ['images', 'documents']) {\n const blobs = request[key];\n if (Array.isArray(blobs)) {\n request[key] = blobs.map(() => BLOB_SUBSTITUTE);\n }\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings') {\n const text = params.text;\n\n if (text == null || (typeof text === 'string' && text.length === 0) || (Array.isArray(text) && text.length === 0)) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(text, String));\n return;\n }\n\n const src = params.messages ?? params.prompt;\n\n if (src == null || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Record the response attributes (token usage, response text, tool calls) on the span.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs: boolean,\n operationName?: WorkersAiOperationName,\n): void {\n if (operationName === 'decide') {\n // The binding wraps the TypeSafe response as `{ state, result }`, but the docs show it unwrapped.\n const body = isObjectLike(result) && isObjectLike(result.result) ? result.result : result;\n addDecideResponseAttributes(span, body, recordOutputs);\n return;\n }\n\n if (operationName === 'extract') {\n addExtractResponseAttributes(span, result, recordOutputs);\n return;\n }\n\n if (\n !result ||\n typeof result !== 'object' ||\n // Raw `Response` objects (from `returnRawResponse`/`websocket`) cannot be introspected without consuming them.\n (typeof Response !== 'undefined' && result instanceof Response)\n ) {\n return;\n }\n\n const response = result as WorkersAiOutput;\n\n if (response.usage) {\n span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));\n }\n\n if (Array.isArray(response.choices)) {\n if (typeof response.id === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_ID, response.id);\n }\n if (typeof response.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model);\n }\n addChoicesResponseAttributes(span, response.choices, recordOutputs);\n return;\n }\n\n if (recordOutputs) {\n let responseText: string | undefined;\n if (typeof response.response === 'string') {\n responseText = response.response;\n span.setAttribute(GEN_AI_RESPONSE_TEXT, response.response);\n } else if (response.response != null) {\n responseText = JSON.stringify(response.response);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, responseText);\n }\n\n const toolCalls =\n Array.isArray(response.tool_calls) && response.tool_calls.length > 0 ? response.tool_calls : undefined;\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n setOutputMessagesAttribute(span, { responseText, toolCalls });\n }\n}\n\nfunction addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void {\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons));\n }\n\n if (!recordOutputs) {\n return;\n }\n\n const messages = choices.map(({ message, finish_reason }) => ({\n responseText: typeof message?.content === 'string' ? message.content : undefined,\n toolCalls: message?.tool_calls,\n finishReason: typeof finish_reason === 'string' ? finish_reason : undefined,\n }));\n\n setOutputMessagesAttribute(span, messages);\n}\n\nfunction addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(body)) {\n return;\n }\n\n const { model, usage, ...response } = body;\n\n if (typeof model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, model);\n }\n\n if (isObjectLike(usage)) {\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.input_tokens === 'number' ? usage.input_tokens : undefined,\n typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined,\n ),\n );\n }\n\n if (recordOutputs) {\n span.set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BAAgB,KAAA;CACpE,EAAE;CAEF,2BAA2B,MAAM,QAAQ;AAC3C;AAEA,SAAS,6BAA6B,MAAY,MAAe,eAA8B;CAC7F,IAAI,CAAC,aAAa,IAAI,GACpB;CAGF,MAAM,EAAE,OAAO,OAAO,GAAG,aAAa;CAEtC,IAAI,OAAO,UAAU,UACnB,KAAK,aAAa,uBAAuB,KAAK;CAGhD,IAAI,aAAa,KAAK,GACpB,KAAK,cACH,wBACE,OAAO,MAAM,iBAAiB,WAAW,MAAM,eAAe,KAAA,GAC9D,OAAO,MAAM,kBAAkB,WAAW,MAAM,gBAAgB,KAAA,CAClE,CACF;CAGF,IAAI,eACF,KAAK,aAAa,wBAAwB,UAAU,CAAC,QAAQ,CAAC,CAAC;AAEnE"}
|
package/build/esm/index.js
CHANGED
|
@@ -53,6 +53,7 @@ import { createFlueInstrumentation } from "./ai/flue/index.js";
|
|
|
53
53
|
import { flueIntegration } from "./integrations/flue.js";
|
|
54
54
|
import { piAiIntegration } from "./integrations/pi-ai.js";
|
|
55
55
|
import { piDurableIntegration } from "./integrations/pi-durable.js";
|
|
56
|
+
import { tanstackAIIntegration } from "./integrations/tanstack-ai.js";
|
|
56
57
|
import { mastraIntegration } from "./integrations/mastra.js";
|
|
57
58
|
import { mcpServerIntegration } from "./integrations/mcp-server.js";
|
|
58
59
|
import { instrumentTunnelServers, makeServeTunnelIntegration } from "./integrations/serveTunnel.js";
|
|
@@ -87,6 +88,6 @@ import { getErrorIntegrations, getTracingIntegrations } from "./integrations/ind
|
|
|
87
88
|
* @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.
|
|
88
89
|
*/
|
|
89
90
|
const attachHapiErrorHandler = attachHapiErrorHandler$1;
|
|
90
|
-
export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, clickhouseIntegration, collectInstalledModules, createFlueInstrumentation, createGetModuleFromFilename, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTunnelServer, instrumentTunnelServers, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, setupHapiErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
|
|
91
|
+
export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, clickhouseIntegration, collectInstalledModules, createFlueInstrumentation, createGetModuleFromFilename, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTunnelServer, instrumentTunnelServers, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, setupHapiErrorHandler, subscribe as subscribeDiagnosticsChannel, tanstackAIIntegration, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
|
|
91
92
|
|
|
92
93
|
//# sourceMappingURL=index.js.map
|
package/build/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport {\n hapiIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupHapiErrorHandler,\n} from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport { instrumentTunnelServers, makeServeTunnelIntegration } from './integrations/serveTunnel';\nexport { instrumentTunnelServer } from './utils/tunnelServer';\nexport { createGetModuleFromFilename } from './utils/module';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { clickhouseIntegration } from './integrations/clickhouse';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport {\n hapiIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupHapiErrorHandler,\n} from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport { tanstackAIIntegration } from './integrations/tanstack-ai';\nexport type { TanstackAIOptions } from './ai/tanstack-ai';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport { instrumentTunnelServers, makeServeTunnelIntegration } from './integrations/serveTunnel';\nexport { instrumentTunnelServer } from './utils/tunnelServer';\nexport { createGetModuleFromFilename } from './utils/module';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { clickhouseIntegration } from './integrations/clickhouse';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
|
|
@@ -97,6 +97,10 @@ function onRequest(request, _reply, hookDone) {
|
|
|
97
97
|
const routeName = getRequestRouteUrl(request);
|
|
98
98
|
const method = request.method || "GET";
|
|
99
99
|
getIsolationScope().setTransactionName(`${method} ${routeName}`);
|
|
100
|
+
if (!getActiveSpan()) {
|
|
101
|
+
hookDone();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
100
104
|
const attributes = {
|
|
101
105
|
[SENTRY_ORIGIN]: ORIGIN,
|
|
102
106
|
[SENTRY_OP]: HANDLER,
|
|
@@ -195,7 +199,7 @@ function handlerWrapper(handler, hookName, spanAttributes = {}) {
|
|
|
195
199
|
if (!request) return handler.call(this, ...args);
|
|
196
200
|
const parentSpan = request[kRequestSpan] ?? void 0;
|
|
197
201
|
const effectiveParentSpan = parentSpan ?? getActiveSpan();
|
|
198
|
-
if (effectiveParentSpan
|
|
202
|
+
if (!effectiveParentSpan || !spanIsSampled(effectiveParentSpan)) return handler.call(this, ...args);
|
|
199
203
|
const handlerName = handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME;
|
|
200
204
|
const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];
|
|
201
205
|
const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : void 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation.js","names":["diagnosticsChannel.subscribe"],"sources":["../../../../src/integrations/fastify/instrumentation.ts"],"sourcesContent":["/*\n * Copyright (c) 2024-present The Fastify team <https://github.com/fastify/fastify#team>\n * SPDX-License-Identifier: MIT\n *\n * NOTICE from the Sentry authors:\n * - Based on: https://github.com/fastify/otel/tree/bae80d6caef4287e7f01ff3c8dc753243706ea86 (@fastify/otel@0.18.1)\n * - Streamlined to the Sentry SDK's needs: dropped the `InstrumentationBase` wrapper, the unused\n * request/lifecycle hooks, `ignorePaths`/`minimatch` support and the OpenTelemetry tracer/context\n * APIs in favor of the Sentry span API.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-this-alias */\n/* eslint-disable max-lines */\n\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n HTTP_ROUTE,\n SENTRY_OP,\n URL_PATH,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n isObjectLike,\n getActiveSpan,\n getClient,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n spanIsSampled,\n startInactiveSpan,\n startSpan,\n withActiveSpan,\n} from '@sentry/core';\nimport type { FastifyInstance } from './types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport { handleFastifyError } from './errors';\n\nconst ORIGIN = 'auto.http.fastify';\n\nconst FASTIFY_HOOKS = [\n 'onRequest',\n 'preParsing',\n 'preValidation',\n 'preHandler',\n 'preSerialization',\n 'onSend',\n 'onResponse',\n 'onError',\n];\nconst ATTRIBUTE_HOOK_NAME = 'hook.name' as const;\nconst ATTRIBUTE_FASTIFY_TYPE = 'fastify.type' as const;\nconst ATTRIBUTE_HOOK_CALLBACK_NAME = 'hook.callback.name' as const;\n\nconst HOOK_TYPE_ROUTE = 'route-hook' as const;\nconst HOOK_TYPE_INSTANCE = 'hook' as const;\nconst HOOK_TYPE_HANDLER = 'request-handler' as const;\nconst ANONYMOUS_FUNCTION_NAME = 'anonymous';\n\nconst kRequestSpan = Symbol('sentry fastify request span');\nconst kAddHookOriginal = Symbol('sentry fastify addHook original');\nconst kSetNotFoundOriginal = Symbol('sentry fastify setNotFoundHandler original');\n\ntype AnyFn = (...args: any[]) => any;\n\n/**\n * Read the matched route URL off a request. Fastify >=4 exposes it on `request.routeOptions.url`,\n * while v3 only has the (since-removed-in-v5) `request.routerPath`.\n */\nfunction getRequestRouteUrl(request: any): string | undefined {\n return request.routeOptions?.url ?? request.routerPath;\n}\n\n/**\n * Detect whether one of a wrapped handler's arguments is the Fastify request. We can't rely on a\n * single property since the route metadata moved from `routerPath` (v3) to `routeOptions` (>=4),\n * so we accept either shape.\n */\nfunction isFastifyRequest(arg: any): boolean {\n return isObjectLike(arg) && !!arg.method && !!arg.url && (!!arg.routeOptions || 'routerPath' in arg);\n}\n\n/**\n * Wire up the request/hook/handler spans and error handling on a Fastify instance.\n *\n * This runs synchronously from the `fastify.initialization` diagnostics channel, which fires while\n * `Fastify()` is still constructing the instance, before any user code runs. Doing it synchronously\n * (rather than via `instance.register()`, which defers the work until the boot phase) is what lets us\n * patch `addHook`/`setNotFoundHandler` in time: `addHook` runs immediately, so hooks a user adds\n * synchronously before `listen()`/`ready()` would otherwise slip through un-instrumented.\n */\nfunction instrumentFastifyInstance(instance: FastifyInstance): void {\n // oxlint-disable-next-line typescript/unbound-method\n instance.decorate(kAddHookOriginal, instance.addHook);\n instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);\n instance.decorateRequest('opentelemetry', function opentelemetry(this: any) {\n return { span: this[kRequestSpan] as Span | null };\n });\n instance.decorateRequest(kRequestSpan, null);\n\n instance.addHook('onRoute', onRoute);\n instance.addHook('onRequest', onRequest);\n instance.addHook('onResponse', onResponse);\n // Must be an async hook: a sync (callback-style) `onError` hook would have to invoke Fastify's\n // `done` callback\n instance.addHook('onError', async (request, reply, error) => {\n handleFastifyError(request, reply, error);\n });\n\n // Patch last, so the hooks we add above go through the original (un-wrapped) `addHook`.\n instance.addHook = addHookPatched;\n instance.setNotFoundHandler = setNotFoundHandlerPatched;\n}\n\nfunction onRoute(this: any, routeOptions: any): void {\n for (const hook of FASTIFY_HOOKS) {\n const handlerLike = routeOptions[hook];\n\n if (typeof handlerLike === 'function') {\n routeOptions[hook] = handlerWrapper(\n handlerLike,\n hook,\n routeHookAttributes(this.pluginName, hook, handlerLike, routeOptions.url),\n );\n } else if (Array.isArray(handlerLike)) {\n routeOptions[hook] = handlerLike.map((handler: AnyFn) =>\n handlerWrapper(handler, hook, routeHookAttributes(this.pluginName, hook, handler, routeOptions.url)),\n );\n }\n }\n\n routeOptions.onSend = appendRouteHook(routeOptions.onSend, finalizeResponseSpanHook);\n routeOptions.onError = appendRouteHook(routeOptions.onError, recordErrorInSpanHook);\n\n routeOptions.handler = handlerWrapper(routeOptions.handler, 'handler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - route-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_HANDLER,\n [HTTP_ROUTE]: routeOptions.url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME,\n });\n}\n\nfunction routeHookAttributes(pluginName: string, hook: string, handler: AnyFn, url: string): Record<string, string> {\n return {\n [ATTRIBUTE_HOOK_NAME]: `${pluginName} - route -> ${hook}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_ROUTE,\n [HTTP_ROUTE]: url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n };\n}\n\nfunction appendRouteHook(existing: AnyFn | AnyFn[] | undefined, hook: AnyFn): AnyFn | AnyFn[] {\n if (existing == null) {\n return hook;\n }\n return Array.isArray(existing) ? [...existing, hook] : [existing, hook];\n}\n\nfunction onRequest(this: any, request: any, _reply: any, hookDone: () => void): void {\n const routeName = getRequestRouteUrl(request);\n const method = request.method || 'GET';\n\n getIsolationScope().setTransactionName(`${method} ${routeName}`);\n\n const attributes: Record<string, string> = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: HANDLER,\n [HTTP_REQUEST_METHOD]: request.method,\n [URL_PATH]: request.url,\n };\n\n const route = getRequestRouteUrl(request);\n if (route != null) {\n attributes[HTTP_ROUTE] = route;\n\n setHttpServerSpanRouteAttribute(route);\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n\n const requestSpan = startInactiveSpan({\n name: isStreamedSpan\n ? route || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : route != null\n ? `${request.method} ${route}`\n : 'request',\n attributes,\n });\n request[kRequestSpan] = requestSpan;\n\n // Set the request span as the active span for the remainder of the request lifecycle, so that\n // downstream hooks/handlers as well as errors captured via the error diagnostics channel are\n // parented to it (otherwise they would attach to the root `http.server` span instead).\n withActiveSpan(requestSpan, () => {\n hookDone();\n });\n}\n\nfunction onResponse(request: any, reply: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone();\n}\n\nfunction finalizeResponseSpanHook(\n request: any,\n reply: any,\n payload: any,\n hookDone: (err: null, payload: any) => void,\n): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n if (reply.statusCode >= 500) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone(null, payload);\n}\n\nfunction recordErrorInSpanHook(request: any, _reply: any, error: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error.message });\n }\n\n hookDone();\n}\n\nfunction addHookPatched(this: any, name: string, hook: AnyFn): FastifyInstance {\n const addHookOriginal = this[kAddHookOriginal];\n\n if (FASTIFY_HOOKS.includes(name)) {\n return addHookOriginal.call(\n this,\n name,\n handlerWrapper(hook, name, {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - ${name}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n }\n\n return addHookOriginal.call(this, name, hook);\n}\n\nfunction setNotFoundHandlerPatched(this: any, hooks: any, handler?: any): void {\n const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];\n\n if (typeof hooks === 'function') {\n setNotFoundHandlerOriginal.call(\n this,\n handlerWrapper(hooks, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n return;\n }\n\n if (hooks.preValidation != null) {\n hooks.preValidation = handlerWrapper(hooks.preValidation, 'notFoundHandler - preValidation', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preValidation.name?.length > 0 ? hooks.preValidation.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n if (hooks.preHandler != null) {\n hooks.preHandler = handlerWrapper(hooks.preHandler, 'notFoundHandler - preHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preHandler.name?.length > 0 ? hooks.preHandler.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n // Fastify allows `setNotFoundHandler(opts)` without a handler, falling back to its built-in 404\n // handler. Forward the (already-wrapped) hooks unchanged so that fallback still applies.\n if (handler == null) {\n setNotFoundHandlerOriginal.call(this, hooks);\n return;\n }\n\n setNotFoundHandlerOriginal.call(\n this,\n hooks,\n handlerWrapper(handler, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n}\n\nfunction getRequestFromArgs(args: any[]): any | null {\n for (const arg of args) {\n if (isFastifyRequest(arg)) {\n return arg;\n }\n }\n return null;\n}\n\nfunction handlerWrapper(handler: AnyFn, hookName: string, spanAttributes: Record<string, string> = {}): AnyFn {\n return function handlerWrapped(this: any, ...args: any[]) {\n const request = getRequestFromArgs(args);\n\n if (!request) {\n return handler.call(this, ...args);\n }\n\n const parentSpan = (request[kRequestSpan] as Span | null) ?? undefined;\n\n // A child of an unsampled span is never sampled either, so skip creating it. Hooks that run after\n // the request span ended (e.g. `onResponse`) fall back to the active span, like `startSpan` would.\n const effectiveParentSpan = parentSpan ?? getActiveSpan();\n if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) {\n return handler.call(this, ...args);\n }\n\n const handlerName = handler.name?.length > 0 ? handler.name : (this.pluginName ?? ANONYMOUS_FUNCTION_NAME);\n\n const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];\n const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : undefined;\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route.\n const isStreamedRequestHandlerSpan = hookType === HOOK_TYPE_HANDLER && !!client && hasSpanStreamingEnabled(client);\n\n const attributeHookName = spanAttributes[ATTRIBUTE_HOOK_NAME];\n\n const name = isStreamedRequestHandlerSpan\n ? spanAttributes[HTTP_ROUTE] || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : op && typeof attributeHookName === 'string'\n ? attributeHookName\n : `${hookName} - ${handlerName}`;\n\n return startSpan(\n {\n name,\n attributes: {\n ...spanAttributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: ORIGIN,\n },\n parentSpan,\n },\n () => handler.call(this, ...args),\n );\n };\n}\n\nlet _isInstrumented = false;\n\n/**\n * Set up the Fastify (>= 3.21.0 < 7) instrumentation by subscribing to the `fastify.initialization`\n * diagnostics channel and synchronously instrumenting every Fastify instance as it is created.\n */\nexport function instrumentFastify(): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n diagnosticsChannel.subscribe('fastify.initialization', message => {\n const fastifyInstance = (message as { fastify?: FastifyInstance }).fastify;\n\n if (fastifyInstance) {\n instrumentFastifyInstance(fastifyInstance);\n }\n });\n}\n"],"mappings":";;;;;;;AA4CA,MAAM,SAAS;AAEf,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,+BAA+B;AAErC,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAEhC,MAAM,eAAe,OAAO,6BAA6B;AACzD,MAAM,mBAAmB,OAAO,iCAAiC;AACjE,MAAM,uBAAuB,OAAO,4CAA4C;;;;;AAQhF,SAAS,mBAAmB,SAAkC;CAC5D,OAAO,QAAQ,cAAc,OAAO,QAAQ;AAC9C;;;;;;AAOA,SAAS,iBAAiB,KAAmB;CAC3C,OAAO,aAAa,GAAG,KAAK,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,IAAI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,CAClC;CACF;AACF;AAEA,IAAI,kBAAkB;;;;;AAMtB,SAAgB,oBAA0B;CACxC,IAAI,iBACF;CAEF,kBAAkB;CAElBA,UAA6B,2BAA0B,YAAW;EAChE,MAAM,kBAAmB,QAA0C;EAEnE,IAAI,iBACF,0BAA0B,eAAe;CAE7C,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"instrumentation.js","names":["diagnosticsChannel.subscribe"],"sources":["../../../../src/integrations/fastify/instrumentation.ts"],"sourcesContent":["/*\n * Copyright (c) 2024-present The Fastify team <https://github.com/fastify/fastify#team>\n * SPDX-License-Identifier: MIT\n *\n * NOTICE from the Sentry authors:\n * - Based on: https://github.com/fastify/otel/tree/bae80d6caef4287e7f01ff3c8dc753243706ea86 (@fastify/otel@0.18.1)\n * - Streamlined to the Sentry SDK's needs: dropped the `InstrumentationBase` wrapper, the unused\n * request/lifecycle hooks, `ignorePaths`/`minimatch` support and the OpenTelemetry tracer/context\n * APIs in favor of the Sentry span API.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-this-alias */\n/* eslint-disable max-lines */\n\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n HTTP_ROUTE,\n SENTRY_OP,\n URL_PATH,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n isObjectLike,\n getActiveSpan,\n getClient,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n spanIsSampled,\n startInactiveSpan,\n startSpan,\n withActiveSpan,\n} from '@sentry/core';\nimport type { FastifyInstance } from './types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport { handleFastifyError } from './errors';\n\nconst ORIGIN = 'auto.http.fastify';\n\nconst FASTIFY_HOOKS = [\n 'onRequest',\n 'preParsing',\n 'preValidation',\n 'preHandler',\n 'preSerialization',\n 'onSend',\n 'onResponse',\n 'onError',\n];\nconst ATTRIBUTE_HOOK_NAME = 'hook.name' as const;\nconst ATTRIBUTE_FASTIFY_TYPE = 'fastify.type' as const;\nconst ATTRIBUTE_HOOK_CALLBACK_NAME = 'hook.callback.name' as const;\n\nconst HOOK_TYPE_ROUTE = 'route-hook' as const;\nconst HOOK_TYPE_INSTANCE = 'hook' as const;\nconst HOOK_TYPE_HANDLER = 'request-handler' as const;\nconst ANONYMOUS_FUNCTION_NAME = 'anonymous';\n\nconst kRequestSpan = Symbol('sentry fastify request span');\nconst kAddHookOriginal = Symbol('sentry fastify addHook original');\nconst kSetNotFoundOriginal = Symbol('sentry fastify setNotFoundHandler original');\n\ntype AnyFn = (...args: any[]) => any;\n\n/**\n * Read the matched route URL off a request. Fastify >=4 exposes it on `request.routeOptions.url`,\n * while v3 only has the (since-removed-in-v5) `request.routerPath`.\n */\nfunction getRequestRouteUrl(request: any): string | undefined {\n return request.routeOptions?.url ?? request.routerPath;\n}\n\n/**\n * Detect whether one of a wrapped handler's arguments is the Fastify request. We can't rely on a\n * single property since the route metadata moved from `routerPath` (v3) to `routeOptions` (>=4),\n * so we accept either shape.\n */\nfunction isFastifyRequest(arg: any): boolean {\n return isObjectLike(arg) && !!arg.method && !!arg.url && (!!arg.routeOptions || 'routerPath' in arg);\n}\n\n/**\n * Wire up the request/hook/handler spans and error handling on a Fastify instance.\n *\n * This runs synchronously from the `fastify.initialization` diagnostics channel, which fires while\n * `Fastify()` is still constructing the instance, before any user code runs. Doing it synchronously\n * (rather than via `instance.register()`, which defers the work until the boot phase) is what lets us\n * patch `addHook`/`setNotFoundHandler` in time: `addHook` runs immediately, so hooks a user adds\n * synchronously before `listen()`/`ready()` would otherwise slip through un-instrumented.\n */\nfunction instrumentFastifyInstance(instance: FastifyInstance): void {\n // oxlint-disable-next-line typescript/unbound-method\n instance.decorate(kAddHookOriginal, instance.addHook);\n instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);\n instance.decorateRequest('opentelemetry', function opentelemetry(this: any) {\n return { span: this[kRequestSpan] as Span | null };\n });\n instance.decorateRequest(kRequestSpan, null);\n\n instance.addHook('onRoute', onRoute);\n instance.addHook('onRequest', onRequest);\n instance.addHook('onResponse', onResponse);\n // Must be an async hook: a sync (callback-style) `onError` hook would have to invoke Fastify's\n // `done` callback\n instance.addHook('onError', async (request, reply, error) => {\n handleFastifyError(request, reply, error);\n });\n\n // Patch last, so the hooks we add above go through the original (un-wrapped) `addHook`.\n instance.addHook = addHookPatched;\n instance.setNotFoundHandler = setNotFoundHandlerPatched;\n}\n\nfunction onRoute(this: any, routeOptions: any): void {\n for (const hook of FASTIFY_HOOKS) {\n const handlerLike = routeOptions[hook];\n\n if (typeof handlerLike === 'function') {\n routeOptions[hook] = handlerWrapper(\n handlerLike,\n hook,\n routeHookAttributes(this.pluginName, hook, handlerLike, routeOptions.url),\n );\n } else if (Array.isArray(handlerLike)) {\n routeOptions[hook] = handlerLike.map((handler: AnyFn) =>\n handlerWrapper(handler, hook, routeHookAttributes(this.pluginName, hook, handler, routeOptions.url)),\n );\n }\n }\n\n routeOptions.onSend = appendRouteHook(routeOptions.onSend, finalizeResponseSpanHook);\n routeOptions.onError = appendRouteHook(routeOptions.onError, recordErrorInSpanHook);\n\n routeOptions.handler = handlerWrapper(routeOptions.handler, 'handler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - route-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_HANDLER,\n [HTTP_ROUTE]: routeOptions.url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME,\n });\n}\n\nfunction routeHookAttributes(pluginName: string, hook: string, handler: AnyFn, url: string): Record<string, string> {\n return {\n [ATTRIBUTE_HOOK_NAME]: `${pluginName} - route -> ${hook}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_ROUTE,\n [HTTP_ROUTE]: url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n };\n}\n\nfunction appendRouteHook(existing: AnyFn | AnyFn[] | undefined, hook: AnyFn): AnyFn | AnyFn[] {\n if (existing == null) {\n return hook;\n }\n return Array.isArray(existing) ? [...existing, hook] : [existing, hook];\n}\n\nfunction onRequest(this: any, request: any, _reply: any, hookDone: () => void): void {\n const routeName = getRequestRouteUrl(request);\n const method = request.method || 'GET';\n\n getIsolationScope().setTransactionName(`${method} ${routeName}`);\n\n // No active parent span means this request is being ignored (e.g. via `ignoreIncomingRequests`),\n // so don't open a span that would become the root of a new trace.\n if (!getActiveSpan()) {\n hookDone();\n return;\n }\n\n const attributes: Record<string, string> = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: HANDLER,\n [HTTP_REQUEST_METHOD]: request.method,\n [URL_PATH]: request.url,\n };\n\n const route = getRequestRouteUrl(request);\n if (route != null) {\n attributes[HTTP_ROUTE] = route;\n\n setHttpServerSpanRouteAttribute(route);\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n\n const requestSpan = startInactiveSpan({\n name: isStreamedSpan\n ? route || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : route != null\n ? `${request.method} ${route}`\n : 'request',\n attributes,\n });\n request[kRequestSpan] = requestSpan;\n\n // Set the request span as the active span for the remainder of the request lifecycle, so that\n // downstream hooks/handlers as well as errors captured via the error diagnostics channel are\n // parented to it (otherwise they would attach to the root `http.server` span instead).\n withActiveSpan(requestSpan, () => {\n hookDone();\n });\n}\n\nfunction onResponse(request: any, reply: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone();\n}\n\nfunction finalizeResponseSpanHook(\n request: any,\n reply: any,\n payload: any,\n hookDone: (err: null, payload: any) => void,\n): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n if (reply.statusCode >= 500) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone(null, payload);\n}\n\nfunction recordErrorInSpanHook(request: any, _reply: any, error: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error.message });\n }\n\n hookDone();\n}\n\nfunction addHookPatched(this: any, name: string, hook: AnyFn): FastifyInstance {\n const addHookOriginal = this[kAddHookOriginal];\n\n if (FASTIFY_HOOKS.includes(name)) {\n return addHookOriginal.call(\n this,\n name,\n handlerWrapper(hook, name, {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - ${name}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n }\n\n return addHookOriginal.call(this, name, hook);\n}\n\nfunction setNotFoundHandlerPatched(this: any, hooks: any, handler?: any): void {\n const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];\n\n if (typeof hooks === 'function') {\n setNotFoundHandlerOriginal.call(\n this,\n handlerWrapper(hooks, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n return;\n }\n\n if (hooks.preValidation != null) {\n hooks.preValidation = handlerWrapper(hooks.preValidation, 'notFoundHandler - preValidation', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preValidation.name?.length > 0 ? hooks.preValidation.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n if (hooks.preHandler != null) {\n hooks.preHandler = handlerWrapper(hooks.preHandler, 'notFoundHandler - preHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preHandler.name?.length > 0 ? hooks.preHandler.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n // Fastify allows `setNotFoundHandler(opts)` without a handler, falling back to its built-in 404\n // handler. Forward the (already-wrapped) hooks unchanged so that fallback still applies.\n if (handler == null) {\n setNotFoundHandlerOriginal.call(this, hooks);\n return;\n }\n\n setNotFoundHandlerOriginal.call(\n this,\n hooks,\n handlerWrapper(handler, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n}\n\nfunction getRequestFromArgs(args: any[]): any | null {\n for (const arg of args) {\n if (isFastifyRequest(arg)) {\n return arg;\n }\n }\n return null;\n}\n\nfunction handlerWrapper(handler: AnyFn, hookName: string, spanAttributes: Record<string, string> = {}): AnyFn {\n return function handlerWrapped(this: any, ...args: any[]) {\n const request = getRequestFromArgs(args);\n\n if (!request) {\n return handler.call(this, ...args);\n }\n\n const parentSpan = (request[kRequestSpan] as Span | null) ?? undefined;\n\n // Without a parent span the request is being ignored, and a child of an unsampled span is never\n // sampled either, so skip creating the span in both cases. Hooks that run after the request span\n // ended (e.g. `onResponse`) fall back to the active span, like `startSpan` would.\n const effectiveParentSpan = parentSpan ?? getActiveSpan();\n if (!effectiveParentSpan || !spanIsSampled(effectiveParentSpan)) {\n return handler.call(this, ...args);\n }\n\n const handlerName = handler.name?.length > 0 ? handler.name : (this.pluginName ?? ANONYMOUS_FUNCTION_NAME);\n\n const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];\n const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : undefined;\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route.\n const isStreamedRequestHandlerSpan = hookType === HOOK_TYPE_HANDLER && !!client && hasSpanStreamingEnabled(client);\n\n const attributeHookName = spanAttributes[ATTRIBUTE_HOOK_NAME];\n\n const name = isStreamedRequestHandlerSpan\n ? spanAttributes[HTTP_ROUTE] || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : op && typeof attributeHookName === 'string'\n ? attributeHookName\n : `${hookName} - ${handlerName}`;\n\n return startSpan(\n {\n name,\n attributes: {\n ...spanAttributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: ORIGIN,\n },\n parentSpan,\n },\n () => handler.call(this, ...args),\n );\n };\n}\n\nlet _isInstrumented = false;\n\n/**\n * Set up the Fastify (>= 3.21.0 < 7) instrumentation by subscribing to the `fastify.initialization`\n * diagnostics channel and synchronously instrumenting every Fastify instance as it is created.\n */\nexport function instrumentFastify(): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n diagnosticsChannel.subscribe('fastify.initialization', message => {\n const fastifyInstance = (message as { fastify?: FastifyInstance }).fastify;\n\n if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