@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
230 lines (229 loc) • 12.2 kB
JavaScript
import { HTTP2_ON_SERVER_STREAM, HTTP_ON_SERVER_REQUEST } from "./constants.js";
import { DEBUG_BUILD } from "../../debug-build.js";
import { debug } from "../../utils/debug-logger.js";
import { safeCallback } from "../../utils/safeCallback.js";
import { isServedTunnelRequest } from "../../utils/tunnel.js";
import { getSpanStatusFromHttpCode } from "../../tracing/spanstatus.js";
import { getNodeTunnelHandler, setHttpServerHandlesTunnel } from "../../utils/tunnelStore.js";
import { getClient, getCurrentScope, getIsolationScope, withIsolationScope } from "../../currentScopes.js";
import { hasSpansEnabled } from "../../utils/hasSpansEnabled.js";
import { getContentLengthFromHeaders, getHostFromHeaders, headersToDict, httpHeadersToSpanAttributes, httpRequestToRequestData } from "../../utils/request.js";
import { patchRequestToCaptureBody } from "./patch-request-to-capture-body.js";
import { getUrlFragment, getUrlQuery, parseStringToURLObject, stripUrlQueryAndFragment } from "../../utils/url.js";
import { recordRequestSession } from "./record-request-session.js";
import { generateSpanId, generateTraceId } from "../../utils/propagationContext.js";
import { continueTrace, startSpanManual } from "../../tracing/trace.js";
import "../../tracing/index.js";
import { hasSpanStreamingEnabled } from "../../tracing/spans/hasSpanStreamingEnabled.js";
import "../../tracing/spans/spanNames.js";
import { safeMathRandom } from "../../utils/randomSafeContext.js";
import { filterCollectedUrl, filterCollectedUrlQuery } from "../../utils/data-collection/filterCollectedUrl.js";
import { getClientIPAddress } from "../../utils/clientIPAddress.js";
import { CLIENT_ADDRESS, CLIENT_PORT, HTTP_REQUEST_BODY_SIZE, HTTP_REQUEST_METHOD, HTTP_RESPONSE_STATUS_CODE, HTTP_RESPONSE_STATUS_TEXT, NETWORK_LOCAL_ADDRESS, NETWORK_LOCAL_PORT, NETWORK_PEER_ADDRESS, NETWORK_PEER_PORT, NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION, NETWORK_TRANSPORT, SENTRY_HTTP_PREFETCH, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SENTRY_SEGMENT_NAME_SOURCE, SERVER_ADDRESS, SERVER_PORT, URL_FRAGMENT, URL_FULL, URL_PATH, URL_QUERY, URL_SCHEME, USER_AGENT_ORIGINAL } from "@sentry/conventions/attributes";
import { HTTP_SERVER } from "@sentry/conventions/op";
// src/integrations/http/server-subscription.ts
const INTEGRATION_NAME = "Http.Server";
const SPANS_INTEGRATION_NAME = "Http.SentryServerSpans";
const lastSentryEmitMap = /* @__PURE__ */ new WeakMap();
const kRequestMark = Symbol.for("sentry_http_server_instrumented");
/** return true if it is NOT already marked */
function markRequest(request) {
return !request[kRequestMark] && (request[kRequestMark] = true);
}
function instrumentServer(options, server) {
const currentEmit = server.emit;
if (currentEmit === lastSentryEmitMap.get(server)) return;
const newEmit = new Proxy(currentEmit, { apply(target, thisArg, args) {
const [event, ...data] = args;
if (event !== "request") return target.apply(thisArg, args);
const client = getClient();
const [request, response] = data;
if (!client || !markRequest(request)) return target.apply(thisArg, args);
if (isServedTunnelRequest(request)) {
if (getNodeTunnelHandler()?.(request, response)) return true;
const tunnelIsolationScope = getIsolationScope().clone();
tunnelIsolationScope.setClient(client);
return withIsolationScope(tunnelIsolationScope, () => target.apply(thisArg, args));
}
DEBUG_BUILD && debug.log(INTEGRATION_NAME, "Handling incoming request");
const isolationScope = getIsolationScope().clone();
isolationScope.setClient(client);
const ipAddress = request.socket?.remoteAddress;
const url = request.url || "/";
const normalizedRequest = httpRequestToRequestData(request);
const { maxRequestBodySize: configuredBodySize, ignoreRequestBody, sessions = true, sessionFlushingDelayMS = 6e4 } = options;
const effectiveBodySize = configuredBodySize ?? (client.getDataCollectionOptions().httpBodies.includes("incomingRequest") ? "medium" : "none");
if (effectiveBodySize !== "none" && !safeCallback(DEBUG_BUILD ? "The `ignoreRequestBody` callback threw an error, ignoring the request body:" : "", () => !!ignoreRequestBody?.(url, request), () => true)) patchRequestToCaptureBody(request, isolationScope, effectiveBodySize, INTEGRATION_NAME);
isolationScope.setSDKProcessingMetadata({
normalizedRequest,
ipAddress
});
const bestEffortTransactionName = `${(request.method || "GET").toUpperCase()} ${stripUrlQueryAndFragment(url)}`;
isolationScope.setTransactionName(bestEffortTransactionName);
if (sessions) recordRequestSession(client, {
requestIsolationScope: isolationScope,
response,
sessionFlushingDelayMS: sessionFlushingDelayMS ?? 6e4
});
return withIsolationScope(isolationScope, () => {
const sentryTrace = normalizedRequest.headers?.["sentry-trace"];
const baggage = normalizedRequest.headers?.["baggage"];
const sentryTraceValue = Array.isArray(sentryTrace) ? sentryTrace[0] : sentryTrace;
return continueTrace({
sentryTrace: sentryTraceValue,
baggage: Array.isArray(baggage) ? baggage[0] : baggage
}, () => {
const propagationContext = getCurrentScope().getPropagationContext();
propagationContext.propagationSpanId = generateSpanId();
if (!sentryTraceValue) {
propagationContext.traceId = generateTraceId();
propagationContext.sampleRand = safeMathRandom();
}
response.once("close", () => {
isolationScope.setContext("response", { status_code: response.statusCode });
});
const wrap = options.wrapServerEmitRequest;
let emitResult = false;
if (wrap) wrap(request, response, normalizedRequest, () => {
emitResult = target.apply(thisArg, args);
});
else emitResult = target.apply(thisArg, args);
return emitResult;
});
});
} });
lastSentryEmitMap.set(server, newEmit);
server.emit = newEmit;
}
function getHttpServerSubscriptions(options) {
const userWrap = options.wrapServerEmitRequest;
const spanWrap = buildServerSpanWrap(options);
setHttpServerHandlesTunnel();
const effectiveOptions = {
...options,
wrapServerEmitRequest(request, response, normalizedRequest, next) {
const clientOptions = getClient()?.getOptions();
if (options.spans ?? (clientOptions ? hasSpansEnabled(clientOptions) : false)) spanWrap(request, response, normalizedRequest, next);
else if (userWrap) userWrap(request, response, normalizedRequest, next);
else next();
}
};
const onHttpServerRequest = (data) => {
const { server } = data;
instrumentServer(effectiveOptions, server);
};
const onHttp2ServerStream = (data) => {
const server = data.stream?.session?.server;
if (server) instrumentServer(effectiveOptions, server);
};
return {
[HTTP_ON_SERVER_REQUEST]: onHttpServerRequest,
[HTTP2_ON_SERVER_STREAM]: onHttp2ServerStream
};
}
function buildServerSpanWrap(options) {
const { wrapServerEmitRequest: userWrap, ignoreIncomingRequests, ignoreStaticAssets = true, onSpanCreated, errorMonitor = "error", onSpanEnd } = options;
return (request, response, normalizedRequest, next) => {
if (typeof __SENTRY_TRACING__ !== "undefined" && !__SENTRY_TRACING__) return next();
return userWrap ? userWrap(request, response, normalizedRequest, createSpan) : createSpan();
function createSpan() {
const client = getIsolationScope().getClient();
if (!client) return next();
const dataCollectionOptions = client.getDataCollectionOptions();
if (shouldIgnoreSpansForIncomingRequest(request, {
ignoreStaticAssets,
ignoreIncomingRequests
})) {
DEBUG_BUILD && debug.log(SPANS_INTEGRATION_NAME, "Skipping span creation for incoming request", request.url);
return next();
}
const fullUrl = normalizedRequest.url || request.url || "/";
const urlObj = parseStringToURLObject(fullUrl);
const httpTargetWithoutQueryFragment = urlObj ? urlObj.pathname : stripUrlQueryAndFragment(fullUrl);
const method = (request.method || "GET").toUpperCase();
const name = hasSpanStreamingEnabled(client) ? request.method?.toUpperCase() || "HTTP" : `${method} ${httpTargetWithoutQueryFragment}`;
const headers = request.headers;
const userAgent = headers["user-agent"];
const httpVersion = request.httpVersion;
const hostname = getHostFromHeaders(headers)?.replace(/^(.*)(:[0-9]{1,5})/, "$1") || "localhost";
const scheme = fullUrl.startsWith("https") ? "https" : "http";
const { socket } = request;
const { localAddress, localPort, remoteAddress, remotePort } = socket ?? {};
const collectClientAddress = client.getDataCollectionOptions().userInfo;
const forwardedAddress = getClientIPAddress(headers);
const clientAddress = forwardedAddress || remoteAddress;
return startSpanManual({
name,
attributes: {
[SENTRY_OP]: HTTP_SERVER,
[SENTRY_ORIGIN]: "auto.http.http_server",
[SENTRY_SEGMENT_NAME_SOURCE]: "url",
[SENTRY_KIND]: "server",
[SERVER_ADDRESS]: hostname,
[SERVER_PORT]: localPort,
[NETWORK_LOCAL_ADDRESS]: localAddress,
[NETWORK_LOCAL_PORT]: localPort,
[CLIENT_ADDRESS]: collectClientAddress ? clientAddress : void 0,
[CLIENT_PORT]: forwardedAddress ? void 0 : remotePort,
[NETWORK_PEER_ADDRESS]: collectClientAddress ? remoteAddress : void 0,
[NETWORK_PEER_PORT]: remotePort,
[SENTRY_HTTP_PREFETCH]: isKnownPrefetchRequest(request) || void 0,
[URL_FULL]: filterCollectedUrl(fullUrl, client),
[URL_PATH]: urlObj?.pathname ?? httpTargetWithoutQueryFragment,
[URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(urlObj?.search), client),
[URL_FRAGMENT]: getUrlFragment(urlObj?.hash),
[HTTP_REQUEST_METHOD]: method,
[NETWORK_PROTOCOL_NAME]: "http",
[NETWORK_PROTOCOL_VERSION]: httpVersion,
[USER_AGENT_ORIGINAL]: userAgent,
[URL_SCHEME]: scheme,
[NETWORK_TRANSPORT]: httpVersion?.toUpperCase() === "QUIC" ? "udp" : "tcp",
[HTTP_REQUEST_BODY_SIZE]: getContentLengthFromHeaders(request.headers),
...httpHeadersToSpanAttributes(normalizedRequest.headers || {}, dataCollectionOptions)
}
}, (span) => {
safeCallback(DEBUG_BUILD ? "The `onSpanCreated` callback threw an error:" : "", () => onSpanCreated?.(span, request, response), () => void 0);
let isEnded = false;
function endSpan(status) {
if (isEnded) return;
isEnded = true;
span.setAttributes({
[HTTP_RESPONSE_STATUS_TEXT]: request.httpVersion === "2.0" ? void 0 : response.statusMessage?.toUpperCase(),
[HTTP_RESPONSE_STATUS_CODE]: response.statusCode,
...httpHeadersToSpanAttributes(headersToDict(response.headers), dataCollectionOptions, "response")
});
span.setStatus(status);
safeCallback(DEBUG_BUILD ? "The `onSpanEnd` callback threw an error:" : "", () => onSpanEnd?.(span, request, response), () => void 0);
span.end();
}
response.once("close", () => {
endSpan(getSpanStatusFromHttpCode(response.statusCode));
});
response.once(errorMonitor, () => {
const httpStatus = getSpanStatusFromHttpCode(response.statusCode);
endSpan(httpStatus.code === 2 ? httpStatus : { code: 2 });
});
next();
});
}
};
}
function shouldIgnoreSpansForIncomingRequest(request, { ignoreStaticAssets, ignoreIncomingRequests }) {
const urlPath = request.url;
const method = request.method?.toUpperCase();
if (method === "OPTIONS" || method === "HEAD" || !urlPath) return true;
if (ignoreStaticAssets && method === "GET" && isStaticAssetRequest(urlPath)) return true;
if (safeCallback(DEBUG_BUILD ? "The `ignoreIncomingRequests` callback threw an error, not ignoring the request:" : "", () => !!ignoreIncomingRequests?.(urlPath, request), () => false)) return true;
return false;
}
function isStaticAssetRequest(urlPath) {
const path = stripUrlQueryAndFragment(urlPath);
if (path.match(/\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)$/)) return true;
if (path.match(/^\/(robots\.txt|sitemap\.xml|manifest\.json|browserconfig\.xml)$/)) return true;
return false;
}
function isKnownPrefetchRequest(req) {
return req.headers["next-router-prefetch"] === "1";
}
export { getHttpServerSubscriptions, instrumentServer, isStaticAssetRequest };
//# sourceMappingURL=server-subscription.js.map