@sentry/server-utils 11.16.0 → 11.17.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 +60 -0
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +116 -56
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
- package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
- package/build/cjs/index.js +299 -168
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +23 -8
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +41 -30
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +6 -2
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +5 -1
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -1
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +10 -13
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js +6 -5
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +21 -17
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/index.js +3 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/clickhouse-sql.js +31 -0
- package/build/esm/integrations/clickhouse-sql.js.map +1 -0
- package/build/esm/integrations/clickhouse.js +88 -0
- package/build/esm/integrations/clickhouse.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +1 -0
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/fastify/instrumentation.js +3 -1
- package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/hapi/index.js +15 -1
- package/build/esm/integrations/hapi/index.js.map +1 -1
- package/build/esm/integrations/index.js +2 -0
- package/build/esm/integrations/index.js.map +1 -1
- package/build/esm/integrations/langchain.js +10 -3
- package/build/esm/integrations/langchain.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/channel-integration-definitions.js +8 -0
- package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
- package/build/esm/orchestrion/config/clickhouse.js +51 -0
- package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
- package/build/esm/orchestrion/config/index.js +2 -0
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/sql.js +37 -16
- package/build/esm/utils/sql.js.map +1 -1
- package/build/types/ai/langchain/embeddings.d.ts +2 -2
- package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +8 -4
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +5 -2
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +10 -2
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +4 -2
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -6
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +10 -1
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/index.d.ts +2 -1
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/clickhouse-sql.d.ts +8 -0
- package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
- package/build/types/integrations/clickhouse.d.ts +11 -0
- package/build/types/integrations/clickhouse.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/hapi/index.d.ts +12 -0
- package/build/types/integrations/hapi/index.d.ts.map +1 -1
- package/build/types/integrations/index.d.ts.map +1 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +12 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
- package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
- package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
- package/build/types/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/utils/sql.d.ts +28 -3
- package/build/types/utils/sql.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { tracingChannel } from "../utils/diagnosticsChannel.js";
|
|
2
|
+
import { CHANNELS } from "../orchestrion/channels.js";
|
|
3
|
+
import { clickhouseModuleNames } from "../orchestrion/config/clickhouse.js";
|
|
4
|
+
import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
|
|
5
|
+
import { bindTracingChannelToSpan } from "../tracing-channel.js";
|
|
6
|
+
import { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from "../utils/sql.js";
|
|
7
|
+
import { CLICKHOUSE_SQL_RULES } from "./clickhouse-sql.js";
|
|
8
|
+
import { DB_COLLECTION_NAME, DB_NAMESPACE, DB_OPERATION_NAME, DB_QUERY_SUMMARY, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
|
|
9
|
+
import { defineIntegration, startInactiveSpan } from "@sentry/core";
|
|
10
|
+
import { DB } from "@sentry/conventions/op";
|
|
11
|
+
// src/integrations/clickhouse.ts
|
|
12
|
+
const INTEGRATION_NAME = "ClickHouse";
|
|
13
|
+
const ORIGIN = "auto.db.clickhouse";
|
|
14
|
+
const DB_SYSTEM_CLICKHOUSE = "clickhouse";
|
|
15
|
+
const _clickhouseIntegration = (() => {
|
|
16
|
+
return {
|
|
17
|
+
name: INTEGRATION_NAME,
|
|
18
|
+
setup(client) {
|
|
19
|
+
invokeOrchestrionInstrumentation(client, clickhouseModuleNames, instrumentClickhouse, []);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
});
|
|
23
|
+
function instrumentClickhouse() {
|
|
24
|
+
const channels = [
|
|
25
|
+
[CHANNELS.CLICKHOUSE_QUERY, "query"],
|
|
26
|
+
[CHANNELS.CLICKHOUSE_COMMAND, "command"],
|
|
27
|
+
[CHANNELS.CLICKHOUSE_EXEC, "exec"],
|
|
28
|
+
[CHANNELS.CLICKHOUSE_INSERT, "insert"],
|
|
29
|
+
[CHANNELS.CLICKHOUSE_WEB_QUERY, "query"],
|
|
30
|
+
[CHANNELS.CLICKHOUSE_WEB_COMMAND, "command"],
|
|
31
|
+
[CHANNELS.CLICKHOUSE_WEB_EXEC, "exec"],
|
|
32
|
+
[CHANNELS.CLICKHOUSE_WEB_INSERT, "insert"],
|
|
33
|
+
[CHANNELS.CLICKHOUSE_COMMON_QUERY, "query"],
|
|
34
|
+
[CHANNELS.CLICKHOUSE_COMMON_COMMAND, "command"],
|
|
35
|
+
[CHANNELS.CLICKHOUSE_COMMON_EXEC, "exec"],
|
|
36
|
+
[CHANNELS.CLICKHOUSE_COMMON_INSERT, "insert"]
|
|
37
|
+
];
|
|
38
|
+
for (const [channelName, method] of channels) bindTracingChannelToSpan(tracingChannel(channelName), (data) => {
|
|
39
|
+
const params = data.arguments[0];
|
|
40
|
+
if (method === "insert" && Array.isArray(params?.values) && params.values.length === 0) return;
|
|
41
|
+
const attributes = {
|
|
42
|
+
[SENTRY_OP]: DB,
|
|
43
|
+
[SENTRY_KIND]: "client",
|
|
44
|
+
[SENTRY_ORIGIN]: ORIGIN,
|
|
45
|
+
...getConnectionAttributes(data.self?.connectionParams, params),
|
|
46
|
+
...method === "insert" ? getInsertAttributes(params) : getSqlQueryAttributes(typeof params?.query === "string" ? params.query : void 0, CLICKHOUSE_SQL_RULES)
|
|
47
|
+
};
|
|
48
|
+
return startInactiveSpan({
|
|
49
|
+
name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_CLICKHOUSE),
|
|
50
|
+
attributes,
|
|
51
|
+
onlyIfParent: true
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function getInsertAttributes(params) {
|
|
56
|
+
const table = typeof params?.table === "string" && params.table ? params.table : void 0;
|
|
57
|
+
return {
|
|
58
|
+
[DB_OPERATION_NAME]: "INSERT",
|
|
59
|
+
[DB_COLLECTION_NAME]: table,
|
|
60
|
+
[DB_QUERY_SUMMARY]: table ? `INSERT ${table}` : "INSERT"
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function getConnectionAttributes(connectionParams, params) {
|
|
64
|
+
const url = connectionParams?.url;
|
|
65
|
+
const user = params?.auth?.username ?? connectionParams?.auth?.username ?? connectionParams?.username;
|
|
66
|
+
return {
|
|
67
|
+
[DB_SYSTEM_NAME]: DB_SYSTEM_CLICKHOUSE,
|
|
68
|
+
[DB_NAMESPACE]: connectionParams?.database,
|
|
69
|
+
[DB_USER]: typeof user === "string" ? user : void 0,
|
|
70
|
+
[SERVER_ADDRESS]: url?.hostname || void 0,
|
|
71
|
+
[SERVER_PORT]: url ? getServerPort(url) : void 0
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function getServerPort(url) {
|
|
75
|
+
if (url.port) return Number(url.port);
|
|
76
|
+
return url.protocol === "https:" ? 443 : 80;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Diagnostics-channel-based `@clickhouse/client` and `@clickhouse/client-web` integration.
|
|
80
|
+
*
|
|
81
|
+
* Subscribes to the channels Sentry's code transform injects into `ClickHouseClient`'s `query`,
|
|
82
|
+
* `command`, `exec` and `insert` methods, and emits a `db` span for each call. Requires the Sentry
|
|
83
|
+
* runtime hook or bundler plugin to be active.
|
|
84
|
+
*/
|
|
85
|
+
const clickhouseIntegration = defineIntegration(_clickhouseIntegration);
|
|
86
|
+
export { clickhouseIntegration };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=clickhouse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clickhouse.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/clickhouse.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_ADDRESS,\n SERVER_PORT,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, SpanAttributes } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { clickhouseModuleNames } from '../orchestrion/config/clickhouse';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from '../utils/sql';\nimport { CLICKHOUSE_SQL_RULES } from './clickhouse-sql';\n\nconst INTEGRATION_NAME = 'ClickHouse' as const;\nconst ORIGIN = 'auto.db.clickhouse';\nconst DB_SYSTEM_CLICKHOUSE = 'clickhouse';\n\ntype ClickHouseMethod = 'query' | 'command' | 'exec' | 'insert';\n\n// The parts of `ClickHouseClient`'s `connectionParams` the span reads. `>=1.10` moved the username\n// into `auth` (which can hold an access token instead); older versions keep it at the top level.\ninterface ClickHouseConnectionParams {\n url?: URL;\n database?: string;\n username?: string;\n auth?: { username?: string };\n}\n\ninterface ClickHouseClient {\n connectionParams?: ClickHouseConnectionParams;\n}\n\n// `query`/`command`/`exec` take `{ query }`, `insert` takes `{ table, values }`. Every method accepts a\n// per-call `auth` override.\ninterface ClickHouseParams {\n query?: unknown;\n table?: unknown;\n values?: unknown;\n auth?: { username?: unknown };\n}\n\n/** Context orchestrion attaches to the channels wrapping `ClickHouseClient`'s methods. */\ninterface ClickHouseChannelContext extends OrchestrionChannelContext {\n arguments: [ClickHouseParams?, ...unknown[]];\n self?: ClickHouseClient;\n}\n\nconst _clickhouseIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, clickhouseModuleNames, instrumentClickhouse, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentClickhouse(): void {\n // The Node and web clients publish the same calls under their own module names. Before 1.23.0,\n // both use `@clickhouse/client-common`.\n const channels: [string, ClickHouseMethod][] = [\n [CHANNELS.CLICKHOUSE_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_INSERT, 'insert'],\n [CHANNELS.CLICKHOUSE_WEB_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_WEB_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_WEB_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_WEB_INSERT, 'insert'],\n [CHANNELS.CLICKHOUSE_COMMON_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_COMMON_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_COMMON_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_COMMON_INSERT, 'insert'],\n ];\n\n for (const [channelName, method] of channels) {\n // Failed calls only get an error status on the span. The error still rejects to the caller, who\n // decides whether to handle it, so it isn't captured here.\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<ClickHouseChannelContext>(channelName), data => {\n const params = data.arguments[0];\n // `insert` with an empty array returns without sending a request.\n if (method === 'insert' && Array.isArray(params?.values) && params.values.length === 0) {\n return undefined;\n }\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n ...getConnectionAttributes(data.self?.connectionParams, params),\n ...(method === 'insert'\n ? getInsertAttributes(params)\n : getSqlQueryAttributes(typeof params?.query === 'string' ? params.query : undefined, CLICKHOUSE_SQL_RULES)),\n };\n\n return startInactiveSpan({\n name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_CLICKHOUSE),\n attributes,\n onlyIfParent: true,\n });\n });\n }\n}\n\n// `insert` builds its `INSERT INTO <table> FORMAT <format>` statement internally, so the span is\n// described from the target table instead of a statement.\nfunction getInsertAttributes(params: ClickHouseParams | undefined): SpanAttributes {\n const table = typeof params?.table === 'string' && params.table ? params.table : undefined;\n return {\n [DB_OPERATION_NAME]: 'INSERT',\n [DB_COLLECTION_NAME]: table,\n [DB_QUERY_SUMMARY]: table ? `INSERT ${table}` : 'INSERT',\n };\n}\n\nfunction getConnectionAttributes(\n connectionParams: ClickHouseConnectionParams | undefined,\n params: ClickHouseParams | undefined,\n): SpanAttributes {\n const url = connectionParams?.url;\n const user = params?.auth?.username ?? connectionParams?.auth?.username ?? connectionParams?.username;\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_CLICKHOUSE,\n [DB_NAMESPACE]: connectionParams?.database,\n [DB_USER]: typeof user === 'string' ? user : undefined,\n [SERVER_ADDRESS]: url?.hostname || undefined,\n [SERVER_PORT]: url ? getServerPort(url) : undefined,\n };\n}\n\n// The client talks HTTP(S), so a URL without an explicit port uses the protocol's default.\nfunction getServerPort(url: URL): number {\n if (url.port) {\n return Number(url.port);\n }\n return url.protocol === 'https:' ? 443 : 80;\n}\n\n/**\n * Diagnostics-channel-based `@clickhouse/client` and `@clickhouse/client-web` integration.\n *\n * Subscribes to the channels Sentry's code transform injects into `ClickHouseClient`'s `query`,\n * `command`, `exec` and `insert` methods, and emits a `db` span for each call. Requires the Sentry\n * runtime hook or bundler plugin to be active.\n */\nexport const clickhouseIntegration = defineIntegration(_clickhouseIntegration);\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,mBAAmB;AACzB,MAAM,SAAS;AACf,MAAM,uBAAuB;AAgC7B,MAAM,gCAAgC;CACpC,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,uBAAuB,sBAAsB,CAAC,CAAC;EAC1F;CACF;AACF;AAEA,SAAS,uBAA6B;CAGpC,MAAM,WAAyC;EAC7C,CAAC,SAAS,kBAAkB,OAAO;EACnC,CAAC,SAAS,oBAAoB,SAAS;EACvC,CAAC,SAAS,iBAAiB,MAAM;EACjC,CAAC,SAAS,mBAAmB,QAAQ;EACrC,CAAC,SAAS,sBAAsB,OAAO;EACvC,CAAC,SAAS,wBAAwB,SAAS;EAC3C,CAAC,SAAS,qBAAqB,MAAM;EACrC,CAAC,SAAS,uBAAuB,QAAQ;EACzC,CAAC,SAAS,yBAAyB,OAAO;EAC1C,CAAC,SAAS,2BAA2B,SAAS;EAC9C,CAAC,SAAS,wBAAwB,MAAM;EACxC,CAAC,SAAS,0BAA0B,QAAQ;CAC9C;CAEA,KAAK,MAAM,CAAC,aAAa,WAAW,UAGlC,yBAAyBA,eAA4D,WAAW,IAAG,SAAQ;EACzG,MAAM,SAAS,KAAK,UAAU;EAE9B,IAAI,WAAW,YAAY,MAAM,QAAQ,QAAQ,MAAM,KAAK,OAAO,OAAO,WAAW,GACnF;EAGF,MAAM,aAA6B;IAChC,YAAY;IACZ,cAAc;IACd,gBAAgB;GACjB,GAAG,wBAAwB,KAAK,MAAM,kBAAkB,MAAM;GAC9D,GAAI,WAAW,WACX,oBAAoB,MAAM,IAC1B,sBAAsB,OAAO,QAAQ,UAAU,WAAW,OAAO,QAAQ,KAAA,GAAW,oBAAoB;EAC9G;EAEA,OAAO,kBAAkB;GACvB,MAAM,6BAA6B,YAAY,oBAAoB;GACnE;GACA,cAAc;EAChB,CAAC;CACH,CAAC;AAEL;AAIA,SAAS,oBAAoB,QAAsD;CACjF,MAAM,QAAQ,OAAO,QAAQ,UAAU,YAAY,OAAO,QAAQ,OAAO,QAAQ,KAAA;CACjF,OAAO;GACJ,oBAAoB;GACpB,qBAAqB;GACrB,mBAAmB,QAAQ,UAAU,UAAU;CAClD;AACF;AAEA,SAAS,wBACP,kBACA,QACgB;CAChB,MAAM,MAAM,kBAAkB;CAC9B,MAAM,OAAO,QAAQ,MAAM,YAAY,kBAAkB,MAAM,YAAY,kBAAkB;CAC7F,OAAO;GACJ,iBAAiB;GACjB,eAAe,kBAAkB;GACjC,UAAU,OAAO,SAAS,WAAW,OAAO,KAAA;GAC5C,iBAAiB,KAAK,YAAY,KAAA;GAClC,cAAc,MAAM,cAAc,GAAG,IAAI,KAAA;CAC5C;AACF;AAGA,SAAS,cAAc,KAAkB;CACvC,IAAI,IAAI,MACN,OAAO,OAAO,IAAI,IAAI;CAExB,OAAO,IAAI,aAAa,WAAW,MAAM;AAC3C;;;;;;;;AASA,MAAa,wBAAwB,kBAAkB,sBAAsB"}
|
|
@@ -186,6 +186,7 @@ function getSpanForLayer(data, options) {
|
|
|
186
186
|
*/
|
|
187
187
|
function getMatchedLayerPath(layer) {
|
|
188
188
|
if (layer.route) return getLayerPath([layer.route.path]);
|
|
189
|
+
if (layer.rawPath !== void 0) return getLayerPath([layer.rawPath]);
|
|
189
190
|
return layer.keys?.length ? void 0 : layer.path || void 0;
|
|
190
191
|
}
|
|
191
192
|
function getLayerType(layer) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation.js","names":[],"sources":["../../../../src/integrations/express/instrumentation.ts"],"sourcesContent":["import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer) ?? getMatchedLayerPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\n/**\n * The path of a matched layer for which no registration event recorded a path. That is the case when the events\n * arrive after the registration calls: Cloudflare delivers the events of calls at module scope with the first\n * request.\n */\nfunction getMatchedLayerPath(layer: ExpressLayer): string | undefined {\n if (layer.route) {\n return getLayerPath([layer.route.path]);\n }\n // A mount path without parameters is equal to the part of the URL that the layer matched.\n return layer.keys?.length ? undefined : layer.path || undefined;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,SAAS;AAKf,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,0BAAkD;CACtD,YAAY;CACZ,iBAAiB;CACjB,QAAQ;AACV;AAEA,MAAM,aAAmB,CAAC;AAE1B,IAAI,kBAAkB;AAEtB,SAAgB,kBACd,SACA,gBACM;CACN,IAAI,iBACF;CAEF,kBAAkB;CAMlB,KAAK,MAAM,eAAe,CAAC,SAAS,kBAAkB,SAAS,eAAe,GAC5E,eAA2C,WAAW,CAAC,CAAC,UAAU;EAChE,OAAO;EACP,YAAY;EACZ,UAAU;EACV,OAAO;EACP,KAAK;CACP,CAAC;CAGH,KAAK,MAAM,eAAe,CAAC,SAAS,gBAAgB,SAAS,aAAa,GAAG;EAC3E,MAAM,UAAU,eAAqC,WAAW;EAEhE,yBAAyB,UAAS,SAAQ,gBAAgB,MAAM,OAAO,GAAG,EACxE,cAAc,OAAO,MAAM;GACzB,KAAK,iBAAiB;EACxB,EACF,CAAC;EAQD,QAAQ,UAAU;GAChB,OAAO;GACP,UAAU;GACV,KAAK;GACL,QAAO,SAAQ,kBAAkB,MAAM,QAAQ,iBAAiB;GAChE,aAAY,SA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S,OAAO;EACrC;EACA,MAAM,iBAAuB;GAC3B,QAAQ;GACR,KAAK,IAAI;EACX;EACA,MAAM,gBAAsB;GAC1B,QAAQ;GACR,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS;GAAY,CAAC;GAChE,KAAK,IAAI;EACX;EACA,IAAI,KAAK,UAAU,QAAQ;EAC3B,IAAI,KAAK,SAAS,OAAO;EACzB,KAAK,iBAAiB;CACxB;CAEA,OAAO;AACT;;;;;;AAOA,SAAS,oBAAoB,OAAyC;CACpE,IAAI,MAAM,OACR,OAAO,aAAa,CAAC,MAAM,MAAM,IAAI,CAAC;CAGxC,OAAO,MAAM,MAAM,SAAS,KAAA,IAAY,MAAM,QAAQ,KAAA;AACxD;AAEA,SAAS,aAAa,OAAuC;CAC3D,IAAI,MAAM,SAAS,UACjB,OAAO;CAGT,IAAI,MAAM,SAAS,oBAAoB,MAAM,SAAS,UACpD,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,MAAc,MAAwB,SAA6C;CACzG,MAAM,EAAE,cAAc,qBAAqB;CAE3C,IAAI,MAAM,QAAQ,gBAAgB,KAAK,iBAAiB,SAAS,IAAI,GACnE,OAAO;CAGT,IAAI,CAAC,MAAM,QAAQ,YAAY,GAC7B,OAAO;CAGT,IAAI;EACF,OAAO,yBAAyB,MAAM,cAAc,IAAI;CAC1D,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"instrumentation.js","names":[],"sources":["../../../../src/integrations/express/instrumentation.ts"],"sourcesContent":["import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer) ?? getMatchedLayerPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\n/**\n * The path of a matched layer for which no registration event recorded a path. That is the case when the events\n * arrive after the registration calls: Cloudflare delivers the events of calls at module scope with the first\n * request.\n */\nfunction getMatchedLayerPath(layer: ExpressLayer): string | undefined {\n if (layer.route) {\n return getLayerPath([layer.route.path]);\n }\n // `router` 2.3.0 and later keep the registered mount path in `rawPath` and no longer store the matched `path`.\n if (layer.rawPath !== undefined) {\n return getLayerPath([layer.rawPath]);\n }\n // A mount path without parameters is equal to the part of the URL that the layer matched.\n return layer.keys?.length ? undefined : layer.path || undefined;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,SAAS;AAKf,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,0BAAkD;CACtD,YAAY;CACZ,iBAAiB;CACjB,QAAQ;AACV;AAEA,MAAM,aAAmB,CAAC;AAE1B,IAAI,kBAAkB;AAEtB,SAAgB,kBACd,SACA,gBACM;CACN,IAAI,iBACF;CAEF,kBAAkB;CAMlB,KAAK,MAAM,eAAe,CAAC,SAAS,kBAAkB,SAAS,eAAe,GAC5E,eAA2C,WAAW,CAAC,CAAC,UAAU;EAChE,OAAO;EACP,YAAY;EACZ,UAAU;EACV,OAAO;EACP,KAAK;CACP,CAAC;CAGH,KAAK,MAAM,eAAe,CAAC,SAAS,gBAAgB,SAAS,aAAa,GAAG;EAC3E,MAAM,UAAU,eAAqC,WAAW;EAEhE,yBAAyB,UAAS,SAAQ,gBAAgB,MAAM,OAAO,GAAG,EACxE,cAAc,OAAO,MAAM;GACzB,KAAK,iBAAiB;EACxB,EACF,CAAC;EAQD,QAAQ,UAAU;GAChB,OAAO;GACP,UAAU;GACV,KAAK;GACL,QAAO,SAAQ,kBAAkB,MAAM,QAAQ,iBAAiB;GAChE,aAAY,SAAQ;IAClB,qBAAqB,IAAI;IACzB,mBAAmB,IAAI;GACzB;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,kBACd,MACA,mBACM;CACN,MAAM,QAAQ,KAAK;CAGnB,IAAI,CAAC,SAA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AI;EACX;EACA,IAAI,KAAK,UAAU,QAAQ;EAC3B,IAAI,KAAK,SAAS,OAAO;EACzB,KAAK,iBAAiB;CACxB;CAEA,OAAO;AACT;;;;;;AAOA,SAAS,oBAAoB,OAAyC;CACpE,IAAI,MAAM,OACR,OAAO,aAAa,CAAC,MAAM,MAAM,IAAI,CAAC;CAGxC,IAAI,MAAM,YAAY,KAAA,GACpB,OAAO,aAAa,CAAC,MAAM,OAAO,CAAC;CAGrC,OAAO,MAAM,MAAM,SAAS,KAAA,IAAY,MAAM,QAAQ,KAAA;AACxD;AAEA,SAAS,aAAa,OAAuC;CAC3D,IAAI,MAAM,SAAS,UACjB,OAAO;CAGT,IAAI,MAAM,SAAS,oBAAoB,MAAM,SAAS,UACpD,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,MAAc,MAAwB,SAA6C;CACzG,MAAM,EAAE,cAAc,qBAAqB;CAE3C,IAAI,MAAM,QAAQ,gBAAgB,KAAK,iBAAiB,SAAS,IAAI,GACnE,OAAO;CAGT,IAAI,CAAC,MAAM,QAAQ,YAAY,GAC7B,OAAO;CAGT,IAAI;EACF,OAAO,yBAAyB,MAAM,cAAc,IAAI;CAC1D,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -2,7 +2,7 @@ import { subscribe } from "../../utils/diagnosticsChannel.js";
|
|
|
2
2
|
import { setHttpServerSpanRouteAttribute } from "../../utils/setHttpServerSpanRouteAttribute.js";
|
|
3
3
|
import { handleFastifyError } from "./errors.js";
|
|
4
4
|
import { HTTP_REQUEST_METHOD, HTTP_RESPONSE_STATUS_CODE, HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from "@sentry/conventions/attributes";
|
|
5
|
-
import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, getClient, getIsolationScope, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan, startSpan, withActiveSpan } from "@sentry/core";
|
|
5
|
+
import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, getActiveSpan, getClient, getIsolationScope, hasSpanStreamingEnabled, isObjectLike, spanIsSampled, startInactiveSpan, startSpan, withActiveSpan } from "@sentry/core";
|
|
6
6
|
import { HANDLER, MIDDLEWARE } from "@sentry/conventions/op";
|
|
7
7
|
// src/integrations/fastify/instrumentation.ts
|
|
8
8
|
const ORIGIN = "auto.http.fastify";
|
|
@@ -194,6 +194,8 @@ function handlerWrapper(handler, hookName, spanAttributes = {}) {
|
|
|
194
194
|
const request = getRequestFromArgs(args);
|
|
195
195
|
if (!request) return handler.call(this, ...args);
|
|
196
196
|
const parentSpan = request[kRequestSpan] ?? void 0;
|
|
197
|
+
const effectiveParentSpan = parentSpan ?? getActiveSpan();
|
|
198
|
+
if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) return handler.call(this, ...args);
|
|
197
199
|
const handlerName = handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME;
|
|
198
200
|
const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];
|
|
199
201
|
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 getClient,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\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 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":";;;;;;;AA0CA,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,QAAQ,CAAC,CAAC,IAAI,gBAAgB,gBAAgB;AAClG;;;;;;;;;;AAWA,SAAS,0BAA0B,UAAiC;CAElE,SAAS,SAAS,kBAAkB,SAAS,OAAO;CACpD,SAAS,SAAS,sBAAsB,SAAS,kBAAkB;CACnE,SAAS,gBAAgB,iBAAiB,SAAS,gBAAyB;EAC1E,OAAO,EAAE,MAAM,KAAK,cAA6B;CACnD,CAAC;CACD,SAAS,gBAAgB,cAAc,IAAI;CAE3C,SAAS,QAAQ,WAAW,OAAO;CACnC,SAAS,QAAQ,aAAa,SAAS;CACvC,SAAS,QAAQ,cAAc,UAAU;CAGzC,SAAS,QAAQ,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SAAgB,UAAkB,iBAAyC,CAAC,GAAU;CAC5G,OAAO,SAAS,eAA0B,GAAG,MAAa;EACxD,MAAM,UAAU,mBAAmB,IAAI;EAEvC,IAAI,CAAC,SACH,OAAO,QAAQ,KAAK,MAAM,GAAG,IAAI;EAGnC,MAAM,aAAc,QAAQ,iBAAiC,KAAA;EAC7D,MAAM,cAAc,QAAQ,MAAM,SAAS,IAAI,QAAQ,OAAQ,KAAK,cAAc;EAElF,MAAM,WAAW,eAAe;EAChC,MAAM,KAAK,aAAa,qBAAqB,aAAa,aAAa,oBAAoB,UAAU,KAAA;EAErG,MAAM,SAAS,UAAU;EAGzB,MAAM,+BAA+B,aAAa,qBAAqB,CAAC,CAAC,UAAU,wBAAwB,MAAM;EAEjH,MAAM,oBAAoB,eAAe;EAEzC,MAAM,OAAO,+BACT,eAAe,eAAe,qCAC9B,MAAM,OAAO,sBAAsB,WACjC,oBACA,GAAG,SAAS,KAAK;EAEvB,OAAO,UACL;GACE;GACA,YAAY;IACV,GAAG;KACF,YAAY;KACZ,gBAAgB;GACnB;GACA;EACF,SACM,QAAQ,KAAK,MAAM,GAAG,IAAI,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 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,QAAQ,CAAC,CAAC,IAAI,gBAAgB,gBAAgB;AAClG;;;;;;;;;;AAWA,SAAS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IAAI,iBACF;CAEF,kBAAkB;CAElBA,UAA6B,2BAA0B,YAAW;EAChE,MAAM,kBAAmB,QAA0C;EAEnE,IAAI,iBACF,0BAA0B,eAAe;CAE7C,CAAC;AACH"}
|
|
@@ -55,6 +55,20 @@ function instrumentHapi(shouldHandleError) {
|
|
|
55
55
|
* `lib/server.js`. Requires the Sentry runtime hook or bundler plugin.
|
|
56
56
|
*/
|
|
57
57
|
const hapiIntegration = defineIntegration(_hapiIntegration);
|
|
58
|
-
|
|
58
|
+
/**
|
|
59
|
+
* Add a Hapi plugin to capture errors to Sentry.
|
|
60
|
+
*
|
|
61
|
+
* @deprecated The error handler is now registered automatically when the Hapi
|
|
62
|
+
* server starts (via the orchestrion `@hapi/hapi` instrumentation), so calling
|
|
63
|
+
* this is no longer necessary. It remains a safe, idempotent operation when the
|
|
64
|
+
* handler is already attached, and is kept for setups where auto-registration is
|
|
65
|
+
* unavailable. This will be removed in a future major version.
|
|
66
|
+
*
|
|
67
|
+
* @param server The Hapi server to attach the error handler to
|
|
68
|
+
*/
|
|
69
|
+
async function setupHapiErrorHandler(server) {
|
|
70
|
+
attachHapiErrorHandler(server);
|
|
71
|
+
}
|
|
72
|
+
export { hapiIntegration, setupHapiErrorHandler };
|
|
59
73
|
|
|
60
74
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/hapi/index.ts"],"sourcesContent":["import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { hapiModuleNames } from '../../orchestrion/config/hapi';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { attachHapiErrorHandler } from './hapi-error-handler';\nimport type { HapiServer, HapiShouldHandleError } from './hapi-types';\nimport { wrapExtArguments, wrapRouteArguments } from './hapi-utils';\n\n// NOTE: same name as the OTel integration by design — when enabled, the OTel\n// 'Hapi' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Hapi' as const;\n\ninterface HapiIntegrationOptions {\n /**\n * Callback deciding whether an error should be captured and sent to Sentry.\n *\n * By default, 5xx errors (and errors without a resolvable status) are sent,\n * while 3xx and 4xx errors are not. The hapi request's `response` carries the\n * resolved HTTP status.\n *\n * @example\n *\n * ```javascript\n * Sentry.init({\n * integrations: [\n * Sentry.hapiIntegration({\n * shouldHandleError(_error, request) {\n * return (request.response?.output?.statusCode ?? request.response?.statusCode ?? 500) >= 500;\n * },\n * }),\n * ],\n * });\n * ```\n */\n shouldHandleError: HapiShouldHandleError;\n}\n\n/**\n * The shape orchestrion's transform attaches to the `@hapi/hapi` route/ext\n * tracing-channel `context` objects.\n *\n * `arguments` is the *live* args array passed to `server.route` / `server.ext`;\n * we mutate it in place to swap handlers for span-creating proxies. `self` is\n * the hapi server instance: the root server has `self.realm.plugin === undefined`,\n * while a plugin's clone server exposes the registering plugin's name there.\n */\ninterface HapiChannelContext extends OrchestrionChannelContext {\n self?: { realm?: { plugin?: string } };\n}\n\n/**\n * The `start`/`initialize` channel `context` shape: `self` is the live server\n * we attach the auto-registered error listener to.\n */\ninterface HapiServerContext extends OrchestrionChannelContext {\n self?: HapiServer;\n}\n\nconst _hapiIntegration = (({ shouldHandleError }: Partial<HapiIntegrationOptions> = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, hapiModuleNames, instrumentHapi, [shouldHandleError], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentHapi(shouldHandleError?: HapiShouldHandleError): void {\n // `subscribe` requires all five lifecycle hooks. We only act on `start`,\n // which orchestrion fires synchronously with the live args array — that's\n // the moment we mutate the handlers in place.\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_ROUTE).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapRouteArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_EXT).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapExtArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n // Auto-register the error handler when the server boots\n // `attachHapiErrorHandler` is idempotent, so hooking both `start` and `initialize` is safe.\n const attachOnStart = {\n start(rawCtx: unknown) {\n const server = (rawCtx as HapiServerContext).self;\n if (server) {\n attachHapiErrorHandler(server, shouldHandleError);\n }\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n };\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_START).subscribe(attachOnStart);\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_INITIALIZE).subscribe(attachOnStart);\n}\n\n/**\n * Diagnostics-channel-based hapi integration. Subscribes to the\n * `orchestrion:@hapi/hapi:route` / `:ext` channels injected into `@hapi/hapi`'s\n * `lib/server.js`. Requires the Sentry runtime hook or bundler plugin.\n */\nexport const hapiIntegration = defineIntegration(_hapiIntegration);\n"],"mappings":";;;;;;;;AAaA,MAAM,mBAAmB;AAgDzB,MAAM,qBAAqB,EAAE,sBAAuD,CAAC,MAAM;CACzF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,gBAAgB,CAAC,iBAAiB,GAAG,EAC7F,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;AAEA,SAAS,eAAe,mBAAiD;CAIvEA,eAAkC,SAAS,UAAU,CAAC,CAAC,UAAU;EAC/D,MAAM,QAAQ;GACZ,MAAM,MAAM;GACZ,mBAAmB,IAAI,WAAW,IAAI,MAAM,OAAO,MAAM;EAC3D;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CAEDA,eAAkC,SAAS,QAAQ,CAAC,CAAC,UAAU;EAC7D,MAAM,QAAQ;GACZ,MAAM,MAAM;GACZ,iBAAiB,IAAI,WAAW,IAAI,MAAM,OAAO,MAAM;EACzD;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CAID,MAAM,gBAAgB;EACpB,MAAM,QAAiB;GACrB,MAAM,SAAU,OAA6B;GAC7C,IAAI,QACF,uBAAuB,QAAQ,iBAAiB;EAEpD;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX;CAEAA,eAAkC,SAAS,UAAU,CAAC,CAAC,UAAU,aAAa;CAC9EA,eAAkC,SAAS,eAAe,CAAC,CAAC,UAAU,aAAa;AACrF;;;;;;AAOA,MAAa,kBAAkB,kBAAkB,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/hapi/index.ts"],"sourcesContent":["import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { hapiModuleNames } from '../../orchestrion/config/hapi';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { attachHapiErrorHandler } from './hapi-error-handler';\nimport type { HapiServer, HapiShouldHandleError } from './hapi-types';\nimport { wrapExtArguments, wrapRouteArguments } from './hapi-utils';\n\n// NOTE: same name as the OTel integration by design — when enabled, the OTel\n// 'Hapi' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Hapi' as const;\n\ninterface HapiIntegrationOptions {\n /**\n * Callback deciding whether an error should be captured and sent to Sentry.\n *\n * By default, 5xx errors (and errors without a resolvable status) are sent,\n * while 3xx and 4xx errors are not. The hapi request's `response` carries the\n * resolved HTTP status.\n *\n * @example\n *\n * ```javascript\n * Sentry.init({\n * integrations: [\n * Sentry.hapiIntegration({\n * shouldHandleError(_error, request) {\n * return (request.response?.output?.statusCode ?? request.response?.statusCode ?? 500) >= 500;\n * },\n * }),\n * ],\n * });\n * ```\n */\n shouldHandleError: HapiShouldHandleError;\n}\n\n/**\n * The shape orchestrion's transform attaches to the `@hapi/hapi` route/ext\n * tracing-channel `context` objects.\n *\n * `arguments` is the *live* args array passed to `server.route` / `server.ext`;\n * we mutate it in place to swap handlers for span-creating proxies. `self` is\n * the hapi server instance: the root server has `self.realm.plugin === undefined`,\n * while a plugin's clone server exposes the registering plugin's name there.\n */\ninterface HapiChannelContext extends OrchestrionChannelContext {\n self?: { realm?: { plugin?: string } };\n}\n\n/**\n * The `start`/`initialize` channel `context` shape: `self` is the live server\n * we attach the auto-registered error listener to.\n */\ninterface HapiServerContext extends OrchestrionChannelContext {\n self?: HapiServer;\n}\n\nconst _hapiIntegration = (({ shouldHandleError }: Partial<HapiIntegrationOptions> = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, hapiModuleNames, instrumentHapi, [shouldHandleError], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentHapi(shouldHandleError?: HapiShouldHandleError): void {\n // `subscribe` requires all five lifecycle hooks. We only act on `start`,\n // which orchestrion fires synchronously with the live args array — that's\n // the moment we mutate the handlers in place.\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_ROUTE).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapRouteArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_EXT).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapExtArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n // Auto-register the error handler when the server boots\n // `attachHapiErrorHandler` is idempotent, so hooking both `start` and `initialize` is safe.\n const attachOnStart = {\n start(rawCtx: unknown) {\n const server = (rawCtx as HapiServerContext).self;\n if (server) {\n attachHapiErrorHandler(server, shouldHandleError);\n }\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n };\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_START).subscribe(attachOnStart);\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_INITIALIZE).subscribe(attachOnStart);\n}\n\n/**\n * Diagnostics-channel-based hapi integration. Subscribes to the\n * `orchestrion:@hapi/hapi:route` / `:ext` channels injected into `@hapi/hapi`'s\n * `lib/server.js`. Requires the Sentry runtime hook or bundler plugin.\n */\nexport const hapiIntegration = defineIntegration(_hapiIntegration);\n\n/**\n * Add a Hapi plugin to capture errors to Sentry.\n *\n * @deprecated The error handler is now registered automatically when the Hapi\n * server starts (via the orchestrion `@hapi/hapi` instrumentation), so calling\n * this is no longer necessary. It remains a safe, idempotent operation when the\n * handler is already attached, and is kept for setups where auto-registration is\n * unavailable. This will be removed in a future major version.\n *\n * @param server The Hapi server to attach the error handler to\n */\nexport async function setupHapiErrorHandler(server: unknown): Promise<void> {\n attachHapiErrorHandler(server as HapiServer);\n}\n"],"mappings":";;;;;;;;AAaA,MAAM,mBAAmB;AAgDzB,MAAM,qBAAqB,EAAE,sBAAuD,CAAC,MAAM;CACzF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,gBAAgB,CAAC,iBAAiB,GAAG,EAC7F,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;AAEA,SAAS,eAAe,mBAAiD;CAIvEA,eAAkC,SAAS,UAAU,CAAC,CAAC,UAAU;EAC/D,MAAM,QAAQ;GACZ,MAAM,MAAM;GACZ,mBAAmB,IAAI,WAAW,IAAI,MAAM,OAAO,MAAM;EAC3D;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CAEDA,eAAkC,SAAS,QAAQ,CAAC,CAAC,UAAU;EAC7D,MAAM,QAAQ;GACZ,MAAM,MAAM;GACZ,iBAAiB,IAAI,WAAW,IAAI,MAAM,OAAO,MAAM;EACzD;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CAID,MAAM,gBAAgB;EACpB,MAAM,QAAiB;GACrB,MAAM,SAAU,OAA6B;GAC7C,IAAI,QACF,uBAAuB,QAAQ,iBAAiB;EAEpD;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX;CAEAA,eAAkC,SAAS,UAAU,CAAC,CAAC,UAAU,aAAa;CAC9EA,eAAkC,SAAS,eAAe,CAAC,CAAC,UAAU,aAAa;AACrF;;;;;;AAOA,MAAa,kBAAkB,kBAAkB,gBAAgB;;;;;;;;;;;;AAajE,eAAsB,sBAAsB,QAAgC;CAC1E,uBAAuB,MAAoB;AAC7C"}
|
|
@@ -30,6 +30,7 @@ import { togetherAIIntegration } from "./together-ai.js";
|
|
|
30
30
|
import { typesafeIntegration } from "./typesafe.js";
|
|
31
31
|
import { postgresJsIntegration } from "./postgresjs/index.js";
|
|
32
32
|
import { neonIntegration } from "./neon.js";
|
|
33
|
+
import { clickhouseIntegration } from "./clickhouse.js";
|
|
33
34
|
import { firebaseIntegration } from "./firebase/index.js";
|
|
34
35
|
import { expressIntegration } from "./express/index.js";
|
|
35
36
|
import { fastifyIntegration } from "./fastify/index.js";
|
|
@@ -73,6 +74,7 @@ function getTracingIntegrations() {
|
|
|
73
74
|
typesafeIntegration(),
|
|
74
75
|
postgresJsIntegration(),
|
|
75
76
|
neonIntegration(),
|
|
77
|
+
clickhouseIntegration(),
|
|
76
78
|
firebaseIntegration(),
|
|
77
79
|
mcpServerIntegration()
|
|
78
80
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/integrations/index.ts"],"sourcesContent":["import { amqplibIntegration } from './amqplib';\nimport { dataloaderIntegration } from './dataloader';\nimport { knexIntegration } from './knex';\nimport { mongoIntegration } from './mongodb';\nimport { graphqlIntegration } from './graphql';\nimport { redisIntegration } from './redis';\nimport { mysqlIntegration } from './mysql';\nimport { mysql2Integration } from './mysql2';\nimport { postgresIntegration } from './pg';\nimport { prismaIntegration } from './prisma';\nimport { tediousIntegration } from './tedious';\nimport { genericPoolIntegration } from './generic-pool';\nimport { kafkaIntegration } from './kafkajs';\nimport { mongooseIntegration } from './mongoose';\nimport { lruMemoizerIntegration } from './lru-memoizer';\nimport { langChainIntegration } from './langchain';\nimport { langGraphIntegration } from './langgraph';\nimport { piAiIntegration } from './pi-ai';\nimport { piDurableIntegration } from './pi-durable';\nimport { mastraIntegration } from './mastra';\nimport { mcpServerIntegration } from './mcp-server';\nimport { vercelAIIntegration } from './vercel-ai';\nimport { openAIIntegration } from './openai';\nimport { anthropicAIIntegration } from './anthropic';\nimport { googleGenAIIntegration } from './google-genai';\nimport { mistralAIIntegration } from './mistral';\nimport { groqIntegration } from './groq';\nimport { togetherAIIntegration } from './together-ai';\nimport { typesafeIntegration } from './typesafe';\nimport { postgresJsIntegration } from './postgresjs';\nimport { neonIntegration } from './neon';\nimport { firebaseIntegration } from './firebase';\nimport { expressIntegration } from './express';\nimport { fastifyIntegration } from './fastify';\nimport { nitroIntegration } from './nitro';\nimport { hapiIntegration } from './hapi';\nimport { honoIntegration } from './hono';\nimport { koaIntegration } from './koa';\nimport type { Integration } from '@sentry/core';\nimport { awsIntegration } from './aws-sdk';\n\n/** These are integrations that are tracing-only integrations. */\nexport function getTracingIntegrations(): Integration[] {\n return [\n graphqlIntegration(),\n mongoIntegration(),\n mongooseIntegration(),\n mysqlIntegration(),\n mysql2Integration(),\n redisIntegration(),\n postgresIntegration(),\n prismaIntegration(),\n tediousIntegration(),\n knexIntegration(),\n genericPoolIntegration(),\n kafkaIntegration(),\n amqplibIntegration(),\n lruMemoizerIntegration(),\n dataloaderIntegration(),\n awsIntegration(),\n // AI providers\n // LangChain must come first to disable AI provider integrations before they instrument\n langChainIntegration(),\n langGraphIntegration(),\n mastraIntegration(),\n piAiIntegration(),\n piDurableIntegration(),\n vercelAIIntegration(),\n openAIIntegration(),\n anthropicAIIntegration(),\n googleGenAIIntegration(),\n mistralAIIntegration(),\n groqIntegration(),\n togetherAIIntegration(),\n typesafeIntegration(),\n postgresJsIntegration(),\n neonIntegration(),\n firebaseIntegration(),\n mcpServerIntegration(),\n ];\n}\n\n/**\n * These are default integrations that are registered regardless of whether tracing is enabled -\n * either because they cover error capture in addition to tracing, or because they handle trace\n * propagation (which must work in tracing-without-performance mode too).\n */\nexport function getErrorIntegrations(): Integration[] {\n return [\n expressIntegration(),\n fastifyIntegration(),\n hapiIntegration(),\n honoIntegration(),\n koaIntegration(),\n nitroIntegration(),\n ];\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/integrations/index.ts"],"sourcesContent":["import { amqplibIntegration } from './amqplib';\nimport { dataloaderIntegration } from './dataloader';\nimport { knexIntegration } from './knex';\nimport { mongoIntegration } from './mongodb';\nimport { graphqlIntegration } from './graphql';\nimport { redisIntegration } from './redis';\nimport { mysqlIntegration } from './mysql';\nimport { mysql2Integration } from './mysql2';\nimport { postgresIntegration } from './pg';\nimport { prismaIntegration } from './prisma';\nimport { tediousIntegration } from './tedious';\nimport { genericPoolIntegration } from './generic-pool';\nimport { kafkaIntegration } from './kafkajs';\nimport { mongooseIntegration } from './mongoose';\nimport { lruMemoizerIntegration } from './lru-memoizer';\nimport { langChainIntegration } from './langchain';\nimport { langGraphIntegration } from './langgraph';\nimport { piAiIntegration } from './pi-ai';\nimport { piDurableIntegration } from './pi-durable';\nimport { mastraIntegration } from './mastra';\nimport { mcpServerIntegration } from './mcp-server';\nimport { vercelAIIntegration } from './vercel-ai';\nimport { openAIIntegration } from './openai';\nimport { anthropicAIIntegration } from './anthropic';\nimport { googleGenAIIntegration } from './google-genai';\nimport { mistralAIIntegration } from './mistral';\nimport { groqIntegration } from './groq';\nimport { togetherAIIntegration } from './together-ai';\nimport { typesafeIntegration } from './typesafe';\nimport { postgresJsIntegration } from './postgresjs';\nimport { neonIntegration } from './neon';\nimport { clickhouseIntegration } from './clickhouse';\nimport { firebaseIntegration } from './firebase';\nimport { expressIntegration } from './express';\nimport { fastifyIntegration } from './fastify';\nimport { nitroIntegration } from './nitro';\nimport { hapiIntegration } from './hapi';\nimport { honoIntegration } from './hono';\nimport { koaIntegration } from './koa';\nimport type { Integration } from '@sentry/core';\nimport { awsIntegration } from './aws-sdk';\n\n/** These are integrations that are tracing-only integrations. */\nexport function getTracingIntegrations(): Integration[] {\n return [\n graphqlIntegration(),\n mongoIntegration(),\n mongooseIntegration(),\n mysqlIntegration(),\n mysql2Integration(),\n redisIntegration(),\n postgresIntegration(),\n prismaIntegration(),\n tediousIntegration(),\n knexIntegration(),\n genericPoolIntegration(),\n kafkaIntegration(),\n amqplibIntegration(),\n lruMemoizerIntegration(),\n dataloaderIntegration(),\n awsIntegration(),\n // AI providers\n // LangChain must come first to disable AI provider integrations before they instrument\n langChainIntegration(),\n langGraphIntegration(),\n mastraIntegration(),\n piAiIntegration(),\n piDurableIntegration(),\n vercelAIIntegration(),\n openAIIntegration(),\n anthropicAIIntegration(),\n googleGenAIIntegration(),\n mistralAIIntegration(),\n groqIntegration(),\n togetherAIIntegration(),\n typesafeIntegration(),\n postgresJsIntegration(),\n neonIntegration(),\n clickhouseIntegration(),\n firebaseIntegration(),\n mcpServerIntegration(),\n ];\n}\n\n/**\n * These are default integrations that are registered regardless of whether tracing is enabled -\n * either because they cover error capture in addition to tracing, or because they handle trace\n * propagation (which must work in tracing-without-performance mode too).\n */\nexport function getErrorIntegrations(): Integration[] {\n return [\n expressIntegration(),\n fastifyIntegration(),\n hapiIntegration(),\n honoIntegration(),\n koaIntegration(),\n nitroIntegration(),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,yBAAwC;CACtD,OAAO;EACL,mBAAmB;EACnB,iBAAiB;EACjB,oBAAoB;EACpB,iBAAiB;EACjB,kBAAkB;EAClB,iBAAiB;EACjB,oBAAoB;EACpB,kBAAkB;EAClB,mBAAmB;EACnB,gBAAgB;EAChB,uBAAuB;EACvB,iBAAiB;EACjB,mBAAmB;EACnB,uBAAuB;EACvB,sBAAsB;EACtB,eAAe;EAGf,qBAAqB;EACrB,qBAAqB;EACrB,kBAAkB;EAClB,gBAAgB;EAChB,qBAAqB;EACrB,oBAAoB;EACpB,kBAAkB;EAClB,uBAAuB;EACvB,uBAAuB;EACvB,qBAAqB;EACrB,gBAAgB;EAChB,sBAAsB;EACtB,oBAAoB;EACpB,sBAAsB;EACtB,gBAAgB;EAChB,sBAAsB;EACtB,oBAAoB;EACpB,qBAAqB;CACvB;AACF;;;;;;AAOA,SAAgB,uBAAsC;CACpD,OAAO;EACL,mBAAmB;EACnB,mBAAmB;EACnB,gBAAgB;EAChB,gBAAgB;EAChB,eAAe;EACf,iBAAiB;CACnB;AACF"}
|
|
@@ -4,6 +4,7 @@ import { GOOGLE_GENAI_INTEGRATION_NAME } from "../ai/google-genai/constants.js";
|
|
|
4
4
|
import { createLangChainCallbackHandler } from "../ai/langchain/index.js";
|
|
5
5
|
import { LANGCHAIN_INTEGRATION_NAME } from "../ai/langchain/constants.js";
|
|
6
6
|
import { _INTERNAL_getLangChainEmbeddingsSpanOptions } from "../ai/langchain/embeddings.js";
|
|
7
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../ai/core/span-hooks.js";
|
|
7
8
|
import { recordTypeSafeClassifierState } from "../ai/langchain/typesafe-classifier.js";
|
|
8
9
|
import { _INTERNAL_mergeLangChainCallbackHandler, getConversationIdMetadataFromConfig, getInheritedLangChainCallbacks } from "../ai/langchain/utils.js";
|
|
9
10
|
import { MISTRAL_INTEGRATION_NAME } from "../ai/mistral/constants.js";
|
|
@@ -63,12 +64,18 @@ function instrumentChatModels(options) {
|
|
|
63
64
|
});
|
|
64
65
|
}
|
|
65
66
|
function instrumentEmbeddings(options) {
|
|
66
|
-
for (const channelName of langchainEmbeddingsChannels) bindTracingChannelToSpan(tracingChannel(channelName), (data) => createEmbeddingsSpan(data, options));
|
|
67
|
+
for (const channelName of langchainEmbeddingsChannels) bindTracingChannelToSpan(tracingChannel(channelName), (data) => createEmbeddingsSpan(data, options), { beforeSpanEnd: (_span, data) => data._sentryOnSpanEnd?.("error" in data ? { error: data.error } : { response: data.result }) });
|
|
67
68
|
}
|
|
68
69
|
function createEmbeddingsSpan(data, options) {
|
|
69
70
|
markProvidersSkipped();
|
|
70
|
-
const
|
|
71
|
-
|
|
71
|
+
const call = {
|
|
72
|
+
operation: "embeddings",
|
|
73
|
+
input: (data.arguments ?? [])[0]
|
|
74
|
+
};
|
|
75
|
+
const span = startInactiveSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(data.self, call, options));
|
|
76
|
+
runGenAiSpanStart(options, span, call);
|
|
77
|
+
data._sentryOnSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
|
|
78
|
+
return span;
|
|
72
79
|
}
|
|
73
80
|
/**
|
|
74
81
|
* Diagnostics-channel-based LangChain integration. Subscribes to the diagnostics_channels
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"langchain.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/langchain.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { _INTERNAL_skipAiProviderWrapping, defineIntegration, startInactiveSpan } from '@sentry/core';\nimport { ANTHROPIC_AI_INTEGRATION_NAME } from '../ai/anthropic-ai/constants';\nimport { GOOGLE_GENAI_INTEGRATION_NAME } from '../ai/google-genai/constants';\nimport { createLangChainCallbackHandler } from '../ai/langchain';\nimport { LANGCHAIN_INTEGRATION_NAME } from '../ai/langchain/constants';\nimport { _INTERNAL_getLangChainEmbeddingsSpanOptions } from '../ai/langchain/embeddings';\nimport { recordTypeSafeClassifierState } from '../ai/langchain/typesafe-classifier';\nimport type { LangChainOptions } from '../ai/langchain/types';\nimport {\n getConversationIdMetadataFromConfig,\n getInheritedLangChainCallbacks,\n _INTERNAL_mergeLangChainCallbackHandler,\n} from '../ai/langchain/utils';\nimport { MISTRAL_INTEGRATION_NAME } from '../ai/mistral/constants';\nimport { OPENAI_INTEGRATION_NAME } from '../ai/openai/constants';\nimport { GROQ_INTEGRATION_NAME } from './groq';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { langchainEmbeddingsChannels } from '../orchestrion/config/langchain';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { langchainModuleNames } from '../orchestrion/config/langchain';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'LangChain' integration is\n// deduplicated out of the default set.\nconst INTEGRATION_NAME = LANGCHAIN_INTEGRATION_NAME;\n\n// LangChain drives the underlying AI provider SDKs itself, so while it's active those providers must\n// not also instrument, or every call would produce two spans (mirrors the OTel path's skip list).\nconst SKIPPED_PROVIDERS = [\n OPENAI_INTEGRATION_NAME,\n ANTHROPIC_AI_INTEGRATION_NAME,\n GOOGLE_GENAI_INTEGRATION_NAME,\n MISTRAL_INTEGRATION_NAME,\n // `@langchain/groq` drives `groq-sdk`, so ChatGroq calls must not also open the Groq integration's span.\n GROQ_INTEGRATION_NAME,\n];\n\n// The chat-model channels carry the live args array of `invoke(input, options)` / `_streamIterator(input, options)`.\n// The embeddings channels carry the instance (`self`) and the `embedQuery(text)` / `embedDocuments(texts)` args.\n// Registered lazily on the first LangChain call (not at `setupOnce`) so a direct provider call made\n// before any LangChain call still gets its own span — matches the OTel patch-on-import timing. It\n// also stops the underlying SDK from double-instrumenting embeddings, whose `embedQuery`/\n// `embedDocuments` call the provider SDK (e.g. `openai`) internally.\nfunction markProvidersSkipped(): void {\n _INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS);\n}\n\nconst _langChainIntegration = ((options: LangChainOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // Chat models only mutate the call args, so they subscribe without the\n // async-context binding. Kept separate so a missing binding never defers\n // them: on the bundler path the wait would push subscription past\n // `Sentry.init()` and early calls would run with no subscriber.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentChatModels, [options], {\n requiresTracingChannelBinding: false,\n });\n // Embeddings open their own spans via `bindTracingChannelToSpan`, which\n // needs the binding.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentEmbeddings, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentChatModels(options: LangChainOptions): void {\n // One stateful handler tracks spans across the whole run tree, just like the OTel path.\n const sentryHandler = createLangChainCallbackHandler(options);\n\n // Chat models: inject the Sentry callback handler into the call options (arg 1). LangChain's own\n // callback dispatch then creates the spans, exactly as in the OTel path, so no span is opened\n // here — a `start` subscriber (which also makes orchestrion wrap the function) is enough.\n const injectHandler = (message: unknown): void => {\n const args = (message as OrchestrionChannelContext).arguments;\n if (!Array.isArray(args)) {\n return;\n }\n\n let callOptions = args[1] as Record<string, unknown> | undefined;\n if (!callOptions || typeof callOptions !== 'object' || Array.isArray(callOptions)) {\n callOptions = {};\n args[1] = callOptions;\n }\n\n // Without callbacks of its own, the call would otherwise lose the parent run and its tracers (e.g. LangSmith).\n callOptions.callbacks = _INTERNAL_mergeLangChainCallbackHandler(\n callOptions.callbacks ?? getInheritedLangChainCallbacks(),\n sentryHandler,\n );\n\n const conversationIdMetadata = getConversationIdMetadataFromConfig(callOptions);\n if (Object.keys(conversationIdMetadata).length) {\n callOptions.metadata = { ...conversationIdMetadata, ...(callOptions.metadata as Record<string, unknown>) };\n }\n };\n\n for (const channelName of [CHANNELS.LANGCHAIN_CHAT_MODEL_INVOKE, CHANNELS.LANGCHAIN_CHAT_MODEL_STREAM]) {\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channelName).start.subscribe(message => {\n markProvidersSkipped();\n injectHandler(message);\n });\n }\n\n // `TypeSafeClassifier` calls Jev with `fetch`, not through a provider SDK, so nothing needs skipping.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.LANGCHAIN_TYPESAFE_CLASSIFIER_INVOKE)\n .start.subscribe(message => {\n injectHandler(message);\n const { self, arguments: args } = message as OrchestrionChannelContext;\n recordTypeSafeClassifierState(self, args?.[0]);\n });\n}\n\n// Embeddings don't use the callback system. Wrap the method in its own span.\n// Embedding errors reject to the caller, so we only open the span (which bindTracingChannelToSpan\n// still marks failed on error) and do not capture them.\nfunction instrumentEmbeddings(options: LangChainOptions): void {\n for (const channelName of langchainEmbeddingsChannels) {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<
|
|
1
|
+
{"version":3,"file":"langchain.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/langchain.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { _INTERNAL_skipAiProviderWrapping, defineIntegration, startInactiveSpan } from '@sentry/core';\nimport { ANTHROPIC_AI_INTEGRATION_NAME } from '../ai/anthropic-ai/constants';\nimport { GOOGLE_GENAI_INTEGRATION_NAME } from '../ai/google-genai/constants';\nimport { createLangChainCallbackHandler } from '../ai/langchain';\nimport { LANGCHAIN_INTEGRATION_NAME } from '../ai/langchain/constants';\nimport { _INTERNAL_getLangChainEmbeddingsSpanOptions } from '../ai/langchain/embeddings';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { recordTypeSafeClassifierState } from '../ai/langchain/typesafe-classifier';\nimport type { LangChainEmbeddingsCallInfo, LangChainOptions } from '../ai/langchain/types';\nimport {\n getConversationIdMetadataFromConfig,\n getInheritedLangChainCallbacks,\n _INTERNAL_mergeLangChainCallbackHandler,\n} from '../ai/langchain/utils';\nimport { MISTRAL_INTEGRATION_NAME } from '../ai/mistral/constants';\nimport { OPENAI_INTEGRATION_NAME } from '../ai/openai/constants';\nimport { GROQ_INTEGRATION_NAME } from './groq';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { langchainEmbeddingsChannels } from '../orchestrion/config/langchain';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { langchainModuleNames } from '../orchestrion/config/langchain';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'LangChain' integration is\n// deduplicated out of the default set.\nconst INTEGRATION_NAME = LANGCHAIN_INTEGRATION_NAME;\n\ntype EmbeddingsChannelContext = OrchestrionChannelContext & {\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n// LangChain drives the underlying AI provider SDKs itself, so while it's active those providers must\n// not also instrument, or every call would produce two spans (mirrors the OTel path's skip list).\nconst SKIPPED_PROVIDERS = [\n OPENAI_INTEGRATION_NAME,\n ANTHROPIC_AI_INTEGRATION_NAME,\n GOOGLE_GENAI_INTEGRATION_NAME,\n MISTRAL_INTEGRATION_NAME,\n // `@langchain/groq` drives `groq-sdk`, so ChatGroq calls must not also open the Groq integration's span.\n GROQ_INTEGRATION_NAME,\n];\n\n// The chat-model channels carry the live args array of `invoke(input, options)` / `_streamIterator(input, options)`.\n// The embeddings channels carry the instance (`self`) and the `embedQuery(text)` / `embedDocuments(texts)` args.\n// Registered lazily on the first LangChain call (not at `setupOnce`) so a direct provider call made\n// before any LangChain call still gets its own span — matches the OTel patch-on-import timing. It\n// also stops the underlying SDK from double-instrumenting embeddings, whose `embedQuery`/\n// `embedDocuments` call the provider SDK (e.g. `openai`) internally.\nfunction markProvidersSkipped(): void {\n _INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS);\n}\n\nconst _langChainIntegration = ((options: LangChainOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // Chat models only mutate the call args, so they subscribe without the\n // async-context binding. Kept separate so a missing binding never defers\n // them: on the bundler path the wait would push subscription past\n // `Sentry.init()` and early calls would run with no subscriber.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentChatModels, [options], {\n requiresTracingChannelBinding: false,\n });\n // Embeddings open their own spans via `bindTracingChannelToSpan`, which\n // needs the binding.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentEmbeddings, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentChatModels(options: LangChainOptions): void {\n // One stateful handler tracks spans across the whole run tree, just like the OTel path.\n const sentryHandler = createLangChainCallbackHandler(options);\n\n // Chat models: inject the Sentry callback handler into the call options (arg 1). LangChain's own\n // callback dispatch then creates the spans, exactly as in the OTel path, so no span is opened\n // here — a `start` subscriber (which also makes orchestrion wrap the function) is enough.\n const injectHandler = (message: unknown): void => {\n const args = (message as OrchestrionChannelContext).arguments;\n if (!Array.isArray(args)) {\n return;\n }\n\n let callOptions = args[1] as Record<string, unknown> | undefined;\n if (!callOptions || typeof callOptions !== 'object' || Array.isArray(callOptions)) {\n callOptions = {};\n args[1] = callOptions;\n }\n\n // Without callbacks of its own, the call would otherwise lose the parent run and its tracers (e.g. LangSmith).\n callOptions.callbacks = _INTERNAL_mergeLangChainCallbackHandler(\n callOptions.callbacks ?? getInheritedLangChainCallbacks(),\n sentryHandler,\n );\n\n const conversationIdMetadata = getConversationIdMetadataFromConfig(callOptions);\n if (Object.keys(conversationIdMetadata).length) {\n callOptions.metadata = { ...conversationIdMetadata, ...(callOptions.metadata as Record<string, unknown>) };\n }\n };\n\n for (const channelName of [CHANNELS.LANGCHAIN_CHAT_MODEL_INVOKE, CHANNELS.LANGCHAIN_CHAT_MODEL_STREAM]) {\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channelName).start.subscribe(message => {\n markProvidersSkipped();\n injectHandler(message);\n });\n }\n\n // `TypeSafeClassifier` calls Jev with `fetch`, not through a provider SDK, so nothing needs skipping.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.LANGCHAIN_TYPESAFE_CLASSIFIER_INVOKE)\n .start.subscribe(message => {\n injectHandler(message);\n const { self, arguments: args } = message as OrchestrionChannelContext;\n recordTypeSafeClassifierState(self, args?.[0]);\n });\n}\n\n// Embeddings don't use the callback system. Wrap the method in its own span.\n// Embedding errors reject to the caller, so we only open the span (which bindTracingChannelToSpan\n// still marks failed on error) and do not capture them.\nfunction instrumentEmbeddings(options: LangChainOptions): void {\n for (const channelName of langchainEmbeddingsChannels) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<EmbeddingsChannelContext>(channelName),\n data => createEmbeddingsSpan(data, options),\n {\n beforeSpanEnd: (_span, data) =>\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result }),\n },\n );\n }\n}\n\nfunction createEmbeddingsSpan(data: EmbeddingsChannelContext, options: LangChainOptions): Span {\n // `embedQuery`/`embedDocuments` call the provider SDK internally, so skip that SDK's own\n // instrumentation before its channel fires (the producer runs at the embeddings channel's `start`).\n markProvidersSkipped();\n\n const call: LangChainEmbeddingsCallInfo = { operation: 'embeddings', input: (data.arguments ?? [])[0] };\n const span = startInactiveSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(data.self, call, options));\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n return span;\n}\n\n/**\n * Diagnostics-channel-based LangChain integration. Subscribes to the diagnostics_channels\n * injected into `@langchain/core`'s `BaseChatModel` (to inject the Sentry callback handler) and into\n * `@langchain/openai`'s embedding methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const langChainIntegration = defineIntegration(_langChainIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,MAAM,mBAAmB;AAQzB,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CAEA;AACF;AAQA,SAAS,uBAA6B;CACpC,iCAAiC,iBAAiB;AACpD;AAEA,MAAM,0BAA0B,UAA4B,CAAC,MAAM;CACjE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GAKZ,iCAAiC,QAAQ,sBAAsB,sBAAsB,CAAC,OAAO,GAAG,EAC9F,+BAA+B,MACjC,CAAC;GAGD,iCAAiC,QAAQ,sBAAsB,sBAAsB,CAAC,OAAO,CAAC;EAChG;CACF;AACF;AAEA,SAAS,qBAAqB,SAAiC;CAE7D,MAAM,gBAAgB,+BAA+B,OAAO;CAK5D,MAAM,iBAAiB,YAA2B;EAChD,MAAM,OAAQ,QAAsC;EACpD,IAAI,CAAC,MAAM,QAAQ,IAAI,GACrB;EAGF,IAAI,cAAc,KAAK;EACvB,IAAI,CAAC,eAAe,OAAO,gBAAgB,YAAY,MAAM,QAAQ,WAAW,GAAG;GACjF,cAAc,CAAC;GACf,KAAK,KAAK;EACZ;EAGA,YAAY,YAAY,wCACtB,YAAY,aAAa,+BAA+B,GACxD,aACF;EAEA,MAAM,yBAAyB,oCAAoC,WAAW;EAC9E,IAAI,OAAO,KAAK,sBAAsB,CAAC,CAAC,QACtC,YAAY,WAAW;GAAE,GAAG;GAAwB,GAAI,YAAY;EAAqC;CAE7G;CAEA,KAAK,MAAM,eAAe,CAAC,SAAS,6BAA6B,SAAS,2BAA2B,GACnGA,eAA6D,WAAW,CAAC,CAAC,MAAM,WAAU,YAAW;EACnG,qBAAqB;EACrB,cAAc,OAAO;CACvB,CAAC;CAIHC,eAC6C,SAAS,oCAAoC,CAAC,CACxF,MAAM,WAAU,YAAW;EAC1B,cAAc,OAAO;EACrB,MAAM,EAAE,MAAM,WAAW,SAAS;EAClC,8BAA8B,MAAM,OAAO,EAAE;CAC/C,CAAC;AACL;AAKA,SAAS,qBAAqB,SAAiC;CAC7D,KAAK,MAAM,eAAe,6BACxB,yBACED,eAA4D,WAAW,IACvE,SAAQ,qBAAqB,MAAM,OAAO,GAC1C,EACE,gBAAgB,OAAO,SACrB,KAAK,mBAAmB,WAAW,OAAO,EAAE,OAAO,KAAK,MAAM,IAAI,EAAE,UAAU,KAAK,OAAO,CAAC,EAC/F,CACF;AAEJ;AAEA,SAAS,qBAAqB,MAAgC,SAAiC;CAG7F,qBAAqB;CAErB,MAAM,OAAoC;EAAE,WAAW;EAAc,QAAQ,KAAK,aAAa,CAAC,EAAA,CAAG;CAAG;CACtG,MAAM,OAAO,kBAAkB,4CAA4C,KAAK,MAAM,MAAM,OAAO,CAAC;CACpG,kBAAkB,SAAS,MAAM,IAAI;CACrC,KAAK,oBAAmB,WAAU,gBAAgB,SAAS,MAAM,MAAM,MAAM;CAE7E,OAAO;AACT;;;;;;AAOA,MAAa,uBAAuB,kBAAkB,qBAAqB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { amqplibChannels } from "./config/amqplib.js";
|
|
2
2
|
import { anthropicAiChannels } from "./config/anthropic-ai.js";
|
|
3
3
|
import { awsSdkChannels } from "./config/aws-sdk.js";
|
|
4
|
+
import { clickhouseChannels } from "./config/clickhouse.js";
|
|
4
5
|
import { cronChannels } from "./config/cron.js";
|
|
5
6
|
import { dataloaderChannels } from "./config/dataloader.js";
|
|
6
7
|
import { expressChannels } from "./config/express.js";
|
|
@@ -62,6 +63,7 @@ const CHANNELS = {
|
|
|
62
63
|
...amqplibChannels,
|
|
63
64
|
...anthropicAiChannels,
|
|
64
65
|
...awsSdkChannels,
|
|
66
|
+
...clickhouseChannels,
|
|
65
67
|
...cronChannels,
|
|
66
68
|
...dataloaderChannels,
|
|
67
69
|
...expressChannels,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channels.js","names":[],"sources":["../../../src/orchestrion/channels.ts"],"sourcesContent":["import { amqplibChannels } from './config/amqplib';\nimport { anthropicAiChannels } from './config/anthropic-ai';\nimport { awsSdkChannels } from './config/aws-sdk';\nimport { cronChannels } from './config/cron';\nimport { dataloaderChannels } from './config/dataloader';\nimport { expressChannels } from './config/express';\nimport { firebaseChannels } from './config/firebase';\nimport { genericPoolChannels } from './config/generic-pool';\nimport { googleGenAiChannels } from './config/google-genai';\nimport { graphqlChannels } from './config/graphql';\nimport { groqChannels } from './config/groq';\nimport { hapiChannels } from './config/hapi';\nimport { honoChannels } from './config/hono';\nimport { ioredisChannels } from './config/ioredis';\nimport { kafkajsChannels } from './config/kafkajs';\nimport { knexChannels } from './config/knex';\nimport { koaChannels } from './config/koa';\nimport { langchainChannels } from './config/langchain';\nimport { langgraphChannels } from './config/langgraph';\nimport { lruMemoizerChannels } from './config/lru-memoizer';\nimport { mastraChannels } from './config/mastra';\nimport { mcpServerChannels } from './config/mcp-server';\nimport { mistralChannels } from './config/mistral';\nimport { mongodbChannels } from './config/mongodb';\nimport { mongooseChannels } from './config/mongoose';\nimport { mysql2Channels } from './config/mysql2';\nimport { mysqlChannels } from './config/mysql';\nimport { neonChannels } from './config/neon';\nimport { nestjsChannels } from './config/nestjs';\nimport { nodeCronChannels } from './config/node-cron';\nimport { nodeScheduleChannels } from './config/node-schedule';\nimport { openaiChannels } from './config/openai';\nimport { pgChannels } from './config/pg';\nimport { piAiChannels } from './config/pi-ai';\nimport { piDurableChannels } from './config/pi-durable';\nimport { postgresJsChannels } from './config/postgres';\nimport { prismaChannels } from './config/prisma';\nimport { redisChannels } from './config/redis';\nimport { remixChannels } from './config/remix';\nimport { tediousChannels } from './config/tedious';\nimport { togetherAiChannels } from './config/together-ai';\nimport { typesafeChannels } from './config/typesafe';\nimport { vercelAiChannels } from './config/vercel-ai';\n\n/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n *\n * Kept sorted alphabetically by module so concurrent additions insert at different\n * points rather than all appending to the end (fewer merge conflicts).\n */\nexport const CHANNELS = {\n ...amqplibChannels,\n ...anthropicAiChannels,\n ...awsSdkChannels,\n ...cronChannels,\n ...dataloaderChannels,\n ...expressChannels,\n ...firebaseChannels,\n ...genericPoolChannels,\n ...googleGenAiChannels,\n ...graphqlChannels,\n ...groqChannels,\n ...hapiChannels,\n ...honoChannels,\n ...ioredisChannels,\n ...kafkajsChannels,\n ...knexChannels,\n ...koaChannels,\n ...langchainChannels,\n ...langgraphChannels,\n ...lruMemoizerChannels,\n ...mastraChannels,\n ...mcpServerChannels,\n ...mistralChannels,\n ...mongodbChannels,\n ...mongooseChannels,\n ...mysql2Channels,\n ...mysqlChannels,\n ...neonChannels,\n ...nestjsChannels,\n ...nodeCronChannels,\n ...nodeScheduleChannels,\n ...openaiChannels,\n ...pgChannels,\n ...piAiChannels,\n ...piDurableChannels,\n ...postgresJsChannels,\n ...prismaChannels,\n ...redisChannels,\n ...remixChannels,\n ...tediousChannels,\n ...togetherAiChannels,\n ...typesafeChannels,\n ...vercelAiChannels,\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"channels.js","names":[],"sources":["../../../src/orchestrion/channels.ts"],"sourcesContent":["import { amqplibChannels } from './config/amqplib';\nimport { anthropicAiChannels } from './config/anthropic-ai';\nimport { awsSdkChannels } from './config/aws-sdk';\nimport { clickhouseChannels } from './config/clickhouse';\nimport { cronChannels } from './config/cron';\nimport { dataloaderChannels } from './config/dataloader';\nimport { expressChannels } from './config/express';\nimport { firebaseChannels } from './config/firebase';\nimport { genericPoolChannels } from './config/generic-pool';\nimport { googleGenAiChannels } from './config/google-genai';\nimport { graphqlChannels } from './config/graphql';\nimport { groqChannels } from './config/groq';\nimport { hapiChannels } from './config/hapi';\nimport { honoChannels } from './config/hono';\nimport { ioredisChannels } from './config/ioredis';\nimport { kafkajsChannels } from './config/kafkajs';\nimport { knexChannels } from './config/knex';\nimport { koaChannels } from './config/koa';\nimport { langchainChannels } from './config/langchain';\nimport { langgraphChannels } from './config/langgraph';\nimport { lruMemoizerChannels } from './config/lru-memoizer';\nimport { mastraChannels } from './config/mastra';\nimport { mcpServerChannels } from './config/mcp-server';\nimport { mistralChannels } from './config/mistral';\nimport { mongodbChannels } from './config/mongodb';\nimport { mongooseChannels } from './config/mongoose';\nimport { mysql2Channels } from './config/mysql2';\nimport { mysqlChannels } from './config/mysql';\nimport { neonChannels } from './config/neon';\nimport { nestjsChannels } from './config/nestjs';\nimport { nodeCronChannels } from './config/node-cron';\nimport { nodeScheduleChannels } from './config/node-schedule';\nimport { openaiChannels } from './config/openai';\nimport { pgChannels } from './config/pg';\nimport { piAiChannels } from './config/pi-ai';\nimport { piDurableChannels } from './config/pi-durable';\nimport { postgresJsChannels } from './config/postgres';\nimport { prismaChannels } from './config/prisma';\nimport { redisChannels } from './config/redis';\nimport { remixChannels } from './config/remix';\nimport { tediousChannels } from './config/tedious';\nimport { togetherAiChannels } from './config/together-ai';\nimport { typesafeChannels } from './config/typesafe';\nimport { vercelAiChannels } from './config/vercel-ai';\n\n/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n *\n * Kept sorted alphabetically by module so concurrent additions insert at different\n * points rather than all appending to the end (fewer merge conflicts).\n */\nexport const CHANNELS = {\n ...amqplibChannels,\n ...anthropicAiChannels,\n ...awsSdkChannels,\n ...clickhouseChannels,\n ...cronChannels,\n ...dataloaderChannels,\n ...expressChannels,\n ...firebaseChannels,\n ...genericPoolChannels,\n ...googleGenAiChannels,\n ...graphqlChannels,\n ...groqChannels,\n ...hapiChannels,\n ...honoChannels,\n ...ioredisChannels,\n ...kafkajsChannels,\n ...knexChannels,\n ...koaChannels,\n ...langchainChannels,\n ...langgraphChannels,\n ...lruMemoizerChannels,\n ...mastraChannels,\n ...mcpServerChannels,\n ...mistralChannels,\n ...mongodbChannels,\n ...mongooseChannels,\n ...mysql2Channels,\n ...mysqlChannels,\n ...neonChannels,\n ...nestjsChannels,\n ...nodeCronChannels,\n ...nodeScheduleChannels,\n ...openaiChannels,\n ...pgChannels,\n ...piAiChannels,\n ...piDurableChannels,\n ...postgresJsChannels,\n ...prismaChannels,\n ...redisChannels,\n ...remixChannels,\n ...tediousChannels,\n ...togetherAiChannels,\n ...typesafeChannels,\n ...vercelAiChannels,\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAa,WAAW;CACtB,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL"}
|
|
@@ -29,6 +29,14 @@ const CHANNEL_INTEGRATION_DEFINITIONS = [
|
|
|
29
29
|
exportName: "neonIntegration",
|
|
30
30
|
modules: ["@neondatabase/serverless"]
|
|
31
31
|
},
|
|
32
|
+
{
|
|
33
|
+
exportName: "clickhouseIntegration",
|
|
34
|
+
modules: [
|
|
35
|
+
"@clickhouse/client",
|
|
36
|
+
"@clickhouse/client-web",
|
|
37
|
+
"@clickhouse/client-common"
|
|
38
|
+
]
|
|
39
|
+
},
|
|
32
40
|
{
|
|
33
41
|
exportName: "prismaIntegration",
|
|
34
42
|
modules: ["@prisma/orm-family-sql"]
|