🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(web-callouts): add rate limits (#14280)
Nimar3cfd53416fa0
diff --git a/web/src/__tests__/server/unit/web-callout-rate-limit.servertest.ts b/web/src/__tests__/server/unit/web-callout-rate-limit.servertest.tsnew file mode 100644index 0000000000..f6ece54512--- /dev/null+++ b/web/src/__tests__/server/unit/web-callout-rate-limit.servertest.ts@@ -0,0 +1,187 @@+import { RateLimiterRes } from "rate-limiter-flexible";++import {+ WEB_CALLOUT_RATE_LIMIT_REDIS_KEY_PREFIX,+ WebCalloutRateLimitService,+ resetWebCalloutInFlightLimitsForTests,+ withWebCalloutInFlightLimit,+} from "@/src/features/web-callouts/server/rateLimit";+import { env } from "@/src/env.mjs";++const mocks = vi.hoisted(() => ({+ consume: vi.fn(),+ options: [] as Array<Record<string, unknown>>,+}));++vi.mock("rate-limiter-flexible", () => {+ class MockRateLimiterRes {+ constructor(public msBeforeNext = 1000) {}+ }++ class MockRateLimiterRedis {+ consume = mocks.consume;++ constructor(options: Record<string, unknown>) {+ mocks.options.push(options);+ }+ }++ return {+ RateLimiterRedis: MockRateLimiterRedis,+ RateLimiterRes: MockRateLimiterRes,+ };+});++vi.mock("@langfuse/shared/src/server", () => ({+ ClickHouseClientManager: {+ getInstance: () => ({ closeAllConnections: vi.fn() }),+ },+ createNewRedisInstance: vi.fn(),+ logger: { debug: vi.fn(), warn: vi.fn() },+ recordIncrement: vi.fn(),+ redis: null,+ redisQueueRetryOptions: {},+}));++describe("web callout rate limiting", () => {+ const originalRateLimitsEnabled = env.LANGFUSE_RATE_LIMITS_ENABLED;+ const context = {+ orgId: "org-1",+ projectId: "project-1",+ endpointId: "endpoint-1",+ userId: "user-1",+ };++ const redis = () =>+ ({+ status: "ready",+ disconnect: vi.fn(),+ }) as any;++ const pending = () => new Promise<never>(() => undefined);+ const expectUnavailable = (promise: Promise<unknown>) =>+ expect(promise).rejects.toMatchObject({+ code: "TOO_MANY_REQUESTS",+ message: "Web callout invocation is temporarily unavailable.",+ });++ beforeEach(() => {+ (env as any).LANGFUSE_RATE_LIMITS_ENABLED = "true";+ WebCalloutRateLimitService.shutdown();+ resetWebCalloutInFlightLimitsForTests();+ mocks.consume.mockReset();+ mocks.consume.mockResolvedValue({});+ mocks.options.length = 0;+ });++ afterEach(() => {+ (env as any).LANGFUSE_RATE_LIMITS_ENABLED = originalRateLimitsEnabled;+ WebCalloutRateLimitService.shutdown();+ resetWebCalloutInFlightLimitsForTests();+ });++ it("uses scoped 10/60 Redis buckets, shares cold connects, and fails closed", async () => {+ const client = redis();+ await WebCalloutRateLimitService.getInstance(client).consume(context);++ expect(mocks.options).toMatchObject([+ {+ keyPrefix: `${WEB_CALLOUT_RATE_LIMIT_REDIS_KEY_PREFIX}:user`,+ points: 10,+ duration: 60,+ },+ {+ keyPrefix: `${WEB_CALLOUT_RATE_LIMIT_REDIS_KEY_PREFIX}:endpoint`,+ points: 60,+ duration: 60,+ },+ ]);+ expect(mocks.options.map(({ storeClient }) => storeClient)).toEqual([+ client,+ client,+ ]);+ expect(mocks.consume.mock.calls).toEqual([+ ["org-1:project-1:endpoint-1:user-1"],+ ["org-1:project-1:endpoint-1"],+ ]);++ WebCalloutRateLimitService.shutdown();+ let resolveConnect: (() => void) | undefined;+ const coldClient = {+ status: "wait",+ connect: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveConnect = () => {+ coldClient.status = "ready";+ resolve();+ };+ }),+ ),+ disconnect: vi.fn(),+ } as any;+ const service = WebCalloutRateLimitService.getInstance(coldClient);+ const concurrentConsumes = Promise.all([+ service.consume(context),+ service.consume({ ...context, userId: "user-2" }),+ ]);+ expect(coldClient.connect).toHaveBeenCalledTimes(1);+ resolveConnect?.();+ await concurrentConsumes;++ WebCalloutRateLimitService.shutdown();+ mocks.options.length = 0;+ (env as any).LANGFUSE_RATE_LIMITS_ENABLED = "false";+ await expect(+ WebCalloutRateLimitService.getInstance(null).consume(context),+ ).resolves.toBeUndefined();+ expect(mocks.options).toHaveLength(0);+ (env as any).LANGFUSE_RATE_LIMITS_ENABLED = "true";++ WebCalloutRateLimitService.shutdown();+ await expectUnavailable(+ WebCalloutRateLimitService.getInstance(null).consume(context),+ );++ WebCalloutRateLimitService.shutdown();+ mocks.consume.mockRejectedValueOnce(new Error("redis down"));+ await expectUnavailable(+ WebCalloutRateLimitService.getInstance(redis()).consume(context),+ );++ WebCalloutRateLimitService.shutdown();+ mocks.consume.mockRejectedValueOnce(new (RateLimiterRes as any)(2300));+ await expect(+ WebCalloutRateLimitService.getInstance(redis()).consume(context),+ ).rejects.toMatchObject({+ code: "TOO_MANY_REQUESTS",+ message:+ "Web callout invocation rate limit exceeded. Please retry in 3 seconds.",+ });+ });++ it("rejects endpoint and process concurrency above local caps", async () => {+ const endpointSlots = Array.from({ length: 5 }, () =>+ withWebCalloutInFlightLimit(context, pending),+ );+ await expect(+ withWebCalloutInFlightLimit(context, async () => "rejected"),+ ).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });+ expect(endpointSlots).toHaveLength(5);++ resetWebCalloutInFlightLimitsForTests();+ const processSlots = Array.from({ length: 25 }, (_, index) =>+ withWebCalloutInFlightLimit(+ { ...context, endpointId: `endpoint-${index}` },+ pending,+ ),+ );+ await expect(+ withWebCalloutInFlightLimit(+ { ...context, endpointId: "endpoint-2" },+ async () => "rejected",+ ),+ ).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });+ expect(processSlots).toHaveLength(25);+ });+});diff --git a/web/src/__tests__/server/web-callouts-trpc.servertest.ts b/web/src/__tests__/server/web-callouts-trpc.servertest.tsindex 7d959cea9e..17a6d4d732 100644--- a/web/src/__tests__/server/web-callouts-trpc.servertest.ts+++ b/web/src/__tests__/server/web-callouts-trpc.servertest.ts@@ -1,9 +1,15 @@import type { Session } from "next-auth";import type { Mock } from "vitest";+import { TRPCError } from "@trpc/server";import { env } from "@/src/env.mjs";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";+import {+ enforceWebCalloutRateLimit,+ recordWebCalloutInvokeMetric,+ withWebCalloutInFlightLimit,+} from "@/src/features/web-callouts/server/rateLimit";import { decrypt } from "@langfuse/shared/encryption";import {fetchWithSecureRedirects,@@ -27,6 +33,14 @@ vi.mock("@langfuse/shared/encryption", async () => {};});+vi.mock("@/src/features/web-callouts/server/rateLimit", () => ({+ enforceWebCalloutRateLimit: vi.fn(),+ recordWebCalloutInvokeMetric: vi.fn(),+ withWebCalloutInFlightLimit: vi.fn(+ async (_context: unknown, fn: () => Promise<unknown>) => fn(),+ ),+}));+vi.mock("@langfuse/shared/src/server", async () => {const actual = await vi.importActual("@langfuse/shared/src/server");return {@@ -310,6 +324,11 @@ describe("webCallouts router", () => {beforeEach(() => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;(env as any).LANGFUSE_ENABLE_WEB_CALLOUTS = "true";+ (enforceWebCalloutRateLimit as Mock).mockResolvedValue(undefined);+ (recordWebCalloutInvokeMetric as Mock).mockReturnValue(undefined);+ (withWebCalloutInFlightLimit as Mock).mockImplementation(+ async (_context: unknown, fn: () => Promise<unknown>) => fn(),+ );(validateWebhookURL as Mock).mockResolvedValue(undefined);(fetchWithSecureRedirects as Mock).mockResolvedValue({response: { ok: true, status: 204 },@@ -571,6 +590,12 @@ describe("webCallouts router", () => {sessionId: null,}),).resolves.toEqual({ success: true, status: 204 });+ expect(enforceWebCalloutRateLimit).toHaveBeenCalledWith({+ orgId,+ projectId,+ endpointId: endpoint.id,+ userId: "user-1",+ });});it("rejects callout metadata and invoke access for project none role", async () => {@@ -660,6 +685,59 @@ describe("webCallouts router", () => {expect(redirectOptions.redirectValidation.validateUrl).toEqual(expect.any(Function),);+ expect(recordWebCalloutInvokeMetric).toHaveBeenCalledWith("attempted", {+ orgId: "org-1",+ projectId,+ endpointId: "endpoint-1",+ userId: "user-1",+ });+ expect(enforceWebCalloutRateLimit).toHaveBeenCalledWith({+ orgId: "org-1",+ projectId,+ endpointId: "endpoint-1",+ userId: "user-1",+ });+ expect(withWebCalloutInFlightLimit).toHaveBeenCalledWith(+ {+ orgId: "org-1",+ projectId,+ endpointId: "endpoint-1",+ userId: "user-1",+ },+ expect.any(Function),+ );+ });++ it("rate limits before target validation and outbound delivery", async () => {+ const { caller, projectId } = await prepare();+ await createEndpoint(caller, projectId);+ vi.clearAllMocks();+ (enforceWebCalloutRateLimit as Mock).mockRejectedValueOnce(+ new TRPCError({+ code: "TOO_MANY_REQUESTS",+ message: "Web callout invocation rate limit exceeded.",+ }),+ );++ await expect(+ caller.webCallouts.invoke({+ projectId,+ traceId: "trace-1",+ observationId: null,+ sessionId: null,+ }),+ ).rejects.toMatchObject({+ code: "TOO_MANY_REQUESTS",+ message: "Web callout invocation rate limit exceeded.",+ });++ expect(getTraceById).not.toHaveBeenCalled();+ expect(validateWebhookURL).not.toHaveBeenCalledWith(+ "https://example.com/callout",+ expect.anything(),+ expect.anything(),+ );+ expect(fetchWithSecureRedirects).not.toHaveBeenCalled();});it("preserves blank existing request header values on update", async () => {diff --git a/web/src/features/web-callouts/server/rateLimit.ts b/web/src/features/web-callouts/server/rateLimit.tsnew file mode 100644index 0000000000..82ff2f5367--- /dev/null+++ b/web/src/features/web-callouts/server/rateLimit.ts@@ -0,0 +1,256 @@+import { TRPCError } from "@trpc/server";+import { RateLimiterRedis, RateLimiterRes } from "rate-limiter-flexible";+import { type Cluster, type Redis } from "ioredis";++import { env } from "@/src/env.mjs";+import { env as sharedEnv } from "@langfuse/shared/src/env";+import {+ createNewRedisInstance,+ logger,+ recordIncrement,+ redisQueueRetryOptions,+} from "@langfuse/shared/src/server";++export const WEB_CALLOUT_RATE_LIMIT_REDIS_KEY_PREFIX =+ "rate-limit:web-callout-invoke";++const REDIS_RETRY_COOLDOWN_MS = 5_000;+const WEB_CALLOUT_RATE_LIMIT_USER_POINTS = 10;+const WEB_CALLOUT_RATE_LIMIT_ENDPOINT_POINTS = 60;+const WEB_CALLOUT_RATE_LIMIT_DURATION_SECONDS = 60;+const WEB_CALLOUT_MAX_IN_FLIGHT_PER_PROCESS = 25;+const WEB_CALLOUT_MAX_IN_FLIGHT_PER_ENDPOINT = 5;++export type WebCalloutLimitContext = {+ orgId: string;+ projectId: string;+ endpointId: string;+ userId: string;+};++type WebCalloutMetricOutcome =+ | "attempted"+ | "sent"+ | "failed"+ | "timed_out"+ | "rate_limited"+ | "rate_limit_unavailable"+ | "concurrency_rejected";++const redisStatus = (redis: Redis | Cluster) =>+ "status" in redis ? redis.status : undefined;++const getRetryAfterSeconds = (msBeforeNext: number | undefined) =>+ Math.max(1, Math.ceil((msBeforeNext ?? 1000) / 1000));++const limitKey = ({+ orgId,+ projectId,+ endpointId,+ userId,+}: WebCalloutLimitContext) => ({+ endpoint: `${orgId}:${projectId}:${endpointId}`,+ user: `${orgId}:${projectId}:${endpointId}:${userId}`,+});++const tooManyRequests = (message: string, retryAfterSeconds?: number) =>+ new TRPCError({+ code: "TOO_MANY_REQUESTS",+ message:+ retryAfterSeconds === undefined+ ? message+ : `${message} Please retry in ${retryAfterSeconds} seconds.`,+ });++export const recordWebCalloutInvokeMetric = (+ outcome: WebCalloutMetricOutcome,+ context: WebCalloutLimitContext,+) => {+ recordIncrement("langfuse.web_callout.invoke", 1, {+ outcome,+ orgId: context.orgId,+ projectId: context.projectId,+ endpointId: context.endpointId,+ });+};++export class WebCalloutRateLimitService {+ private static instance: WebCalloutRateLimitService | null = null;+ private static redis: Redis | Cluster | null = null;++ private redisUnavailableUntilMs = 0;+ private redisConnectPromise: Promise<void> | null = null;++ public static getInstance(redis?: Redis | Cluster | null) {+ if (!WebCalloutRateLimitService.instance || redis !== undefined) {+ WebCalloutRateLimitService.redis =+ redis !== undefined+ ? redis+ : createNewRedisInstance({+ keyPrefix: sharedEnv.REDIS_KEY_PREFIX ?? undefined,+ enableAutoPipelining: false,+ enableOfflineQueue: false,+ lazyConnect: true,+ ...redisQueueRetryOptions,+ });+ WebCalloutRateLimitService.instance = new WebCalloutRateLimitService();+ }++ return WebCalloutRateLimitService.instance;+ }++ public static shutdown() {+ const redis = WebCalloutRateLimitService.redis;+ if (redis && redisStatus(redis) !== "end") {+ redis.disconnect();+ }+ WebCalloutRateLimitService.redis = null;+ WebCalloutRateLimitService.instance = null;+ }++ public async consume(context: WebCalloutLimitContext) {+ if (env.LANGFUSE_RATE_LIMITS_ENABLED === "false") {+ return;+ }++ const redis = WebCalloutRateLimitService.redis;++ if (!redis) {+ this.failClosed(context, "Redis is not configured for web callouts");+ }++ if (Date.now() < this.redisUnavailableUntilMs) {+ this.failClosed(context, "Redis is temporarily unavailable");+ }++ try {+ await this.ensureRedisReady(redis);+ } catch (error) {+ this.markRedisUnavailable(context, error);+ }++ const keys = limitKey(context);+ const userLimiter = new RateLimiterRedis({+ storeClient: redis,+ keyPrefix: `${WEB_CALLOUT_RATE_LIMIT_REDIS_KEY_PREFIX}:user`,+ points: WEB_CALLOUT_RATE_LIMIT_USER_POINTS,+ duration: WEB_CALLOUT_RATE_LIMIT_DURATION_SECONDS,+ rejectIfRedisNotReady: true,+ });+ const endpointLimiter = new RateLimiterRedis({+ storeClient: redis,+ keyPrefix: `${WEB_CALLOUT_RATE_LIMIT_REDIS_KEY_PREFIX}:endpoint`,+ points: WEB_CALLOUT_RATE_LIMIT_ENDPOINT_POINTS,+ duration: WEB_CALLOUT_RATE_LIMIT_DURATION_SECONDS,+ rejectIfRedisNotReady: true,+ });++ await this.consumeLimiter(userLimiter, keys.user, context);+ await this.consumeLimiter(endpointLimiter, keys.endpoint, context);+ }++ private async ensureRedisReady(redis: Redis | Cluster) {+ if (redisStatus(redis) === "ready") {+ return;+ }++ this.redisConnectPromise ??= redis.connect().finally(() => {+ this.redisConnectPromise = null;+ });++ await this.redisConnectPromise;+ }++ private async consumeLimiter(+ limiter: RateLimiterRedis,+ key: string,+ context: WebCalloutLimitContext,+ ) {+ try {+ await limiter.consume(key);+ } catch (error) {+ if (error instanceof RateLimiterRes) {+ recordWebCalloutInvokeMetric("rate_limited", context);+ throw tooManyRequests(+ "Web callout invocation rate limit exceeded.",+ getRetryAfterSeconds(error.msBeforeNext),+ );+ }++ this.markRedisUnavailable(context, error);+ }+ }++ private markRedisUnavailable(+ context: WebCalloutLimitContext,+ error: unknown,+ ): never {+ this.redisUnavailableUntilMs = Date.now() + REDIS_RETRY_COOLDOWN_MS;+ logger.warn("Web callout rate limiter unavailable", {+ orgId: context.orgId,+ projectId: context.projectId,+ endpointId: context.endpointId,+ error: error instanceof Error ? error.message : "Unknown error",+ });+ this.failClosed(context, "Redis is temporarily unavailable");+ }++ private failClosed(context: WebCalloutLimitContext, reason: string): never {+ recordWebCalloutInvokeMetric("rate_limit_unavailable", context);+ logger.warn("Web callout invocation blocked because rate limiting failed", {+ orgId: context.orgId,+ projectId: context.projectId,+ endpointId: context.endpointId,+ reason,+ });+ throw tooManyRequests("Web callout invocation is temporarily unavailable.");+ }+}++export const enforceWebCalloutRateLimit = async (+ context: WebCalloutLimitContext,+) => {+ await WebCalloutRateLimitService.getInstance().consume(context);+};++let activeWebCallouts = 0;+const activeWebCalloutsByEndpoint = new Map<string, number>();++export const resetWebCalloutInFlightLimitsForTests = () => {+ activeWebCallouts = 0;+ activeWebCalloutsByEndpoint.clear();+};++export const withWebCalloutInFlightLimit = async <T>(+ context: WebCalloutLimitContext,+ fn: () => Promise<T>,+): Promise<T> => {+ const endpointKey = limitKey(context).endpoint;+ const activeForEndpoint = activeWebCalloutsByEndpoint.get(endpointKey) ?? 0;++ if (+ activeWebCallouts >= WEB_CALLOUT_MAX_IN_FLIGHT_PER_PROCESS ||+ activeForEndpoint >= WEB_CALLOUT_MAX_IN_FLIGHT_PER_ENDPOINT+ ) {+ recordWebCalloutInvokeMetric("concurrency_rejected", context);+ throw tooManyRequests(+ "Too many web callouts are already in flight. Please retry shortly.",+ );+ }++ activeWebCallouts += 1;+ activeWebCalloutsByEndpoint.set(endpointKey, activeForEndpoint + 1);++ try {+ return await fn();+ } finally {+ activeWebCallouts -= 1;+ const nextActiveForEndpoint =+ (activeWebCalloutsByEndpoint.get(endpointKey) ?? 1) - 1;+ if (nextActiveForEndpoint <= 0) {+ activeWebCalloutsByEndpoint.delete(endpointKey);+ } else {+ activeWebCalloutsByEndpoint.set(endpointKey, nextActiveForEndpoint);+ }+ }+};diff --git a/web/src/features/web-callouts/server/router.ts b/web/src/features/web-callouts/server/router.tsindex 0ee94272f3..61ba583958 100644--- a/web/src/features/web-callouts/server/router.ts+++ b/web/src/features/web-callouts/server/router.ts@@ -171,6 +171,10 @@ export const webCalloutsRouter = createTRPCRouter({prisma: ctx.prisma,input,useEventsTable: ctx.session.user.v4BetaEnabled === true,+ invoker: {+ orgId: ctx.session.orgId,+ userId: ctx.session.user.id,+ },});}),});diff --git a/web/src/features/web-callouts/server/service.ts b/web/src/features/web-callouts/server/service.tsindex a9ec54f4df..464162a571 100644--- a/web/src/features/web-callouts/server/service.ts+++ b/web/src/features/web-callouts/server/service.ts@@ -15,6 +15,12 @@ import {validateWebCalloutUrl,webCalloutWhitelist,} from "@/src/features/web-callouts/server/urlValidation";+import {+ enforceWebCalloutRateLimit,+ recordWebCalloutInvokeMetric,+ withWebCalloutInFlightLimit,+ type WebCalloutLimitContext,+} from "@/src/features/web-callouts/server/rateLimit";import { fetchWithSecureRedirects, logger } from "@langfuse/shared/src/server";import {type PrismaClient,@@ -141,10 +147,15 @@ export const invokeWebCalloutEndpoint = async ({prisma,input,useEventsTable,+ invoker,}: {prisma: PrismaClient;input: WebCalloutInvokeInput;useEventsTable: boolean;+ invoker: {+ orgId: string;+ userId: string;+ };}) => {const endpoint = await prisma.webCalloutEndpoint.findFirst({where: {@@ -161,103 +172,119 @@ export const invokeWebCalloutEndpoint = async ({});}- await assertTargetBelongsToProject({- prisma,- input,- useEventsTable,- });- await assertValidCalloutUrl(endpoint.url);-- const payload: WebCalloutPayload = {- version: 1,- items: [- {- projectId: input.projectId,- traceId: input.traceId,- observationId: input.observationId,- sessionId: input.sessionId,- },- ],+ const limitContext: WebCalloutLimitContext = {+ orgId: invoker.orgId,+ projectId: input.projectId,+ endpointId: endpoint.id,+ userId: invoker.userId,};- const body = JSON.stringify(payload);- const decryptedHeaders = decryptWebCalloutHeaders(endpoint.requestHeaders);- const outboundHeaders = new Headers();- outboundHeaders.set("Content-Type", "application/json");- outboundHeaders.set("User-Agent", "Langfuse/1.0");-- for (const [name, value] of Object.entries(decryptedHeaders)) {- outboundHeaders.set(name, value);- }- const abortController = new AbortController();- const timeout = setTimeout(- () => abortController.abort(),- WEB_CALLOUT_TIMEOUT_MS,- );+ recordWebCalloutInvokeMetric("attempted", limitContext);+ await enforceWebCalloutRateLimit(limitContext);- try {- const { response } = await fetchWithSecureRedirects(- endpoint.url,- {- method: "POST",- body,- headers: outboundHeaders,- signal: abortController.signal,- },- {- maxRedirects: WEB_CALLOUT_MAX_REDIRECTS,- additionalSensitiveHeaders: Object.keys(decryptedHeaders),- redirectValidation: {- validateUrl: validateWebCalloutUrl,- whitelist: webCalloutWhitelist(),- logContext: "Web callout",+ return await withWebCalloutInFlightLimit(limitContext, async () => {+ await assertTargetBelongsToProject({+ prisma,+ input,+ useEventsTable,+ });+ await assertValidCalloutUrl(endpoint.url);++ const payload: WebCalloutPayload = {+ version: 1,+ items: [+ {+ projectId: input.projectId,+ traceId: input.traceId,+ observationId: input.observationId,+ sessionId: input.sessionId,},- },+ ],+ };+ const body = JSON.stringify(payload);+ const decryptedHeaders = decryptWebCalloutHeaders(endpoint.requestHeaders);+ const outboundHeaders = new Headers();+ outboundHeaders.set("Content-Type", "application/json");+ outboundHeaders.set("User-Agent", "Langfuse/1.0");++ for (const [name, value] of Object.entries(decryptedHeaders)) {+ outboundHeaders.set(name, value);+ }++ const abortController = new AbortController();+ const timeout = setTimeout(+ () => abortController.abort(),+ WEB_CALLOUT_TIMEOUT_MS,);- await discardResponseBody(response);- if (!response.ok) {- logger.warn("Web callout returned non-2xx status", {- projectId: input.projectId,- endpointId: endpoint.id,+ try {+ const { response } = await fetchWithSecureRedirects(+ endpoint.url,+ {+ method: "POST",+ body,+ headers: outboundHeaders,+ signal: abortController.signal,+ },+ {+ maxRedirects: WEB_CALLOUT_MAX_REDIRECTS,+ additionalSensitiveHeaders: Object.keys(decryptedHeaders),+ redirectValidation: {+ validateUrl: validateWebCalloutUrl,+ whitelist: webCalloutWhitelist(),+ logContext: "Web callout",+ },+ },+ );+ await discardResponseBody(response);++ if (!response.ok) {+ recordWebCalloutInvokeMetric("failed", limitContext);+ logger.warn("Web callout returned non-2xx status", {+ projectId: input.projectId,+ endpointId: endpoint.id,+ status: response.status,+ });++ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Web callout endpoint returned HTTP ${response.status}.`,+ });+ }++ recordWebCalloutInvokeMetric("sent", limitContext);+ return {+ success: true as const,status: response.status,- });+ };+ } catch (error) {+ if (error instanceof TRPCError) {+ throw error;+ }- throw new TRPCError({- code: "BAD_REQUEST",- message: `Web callout endpoint returned HTTP ${response.status}.`,+ logger.warn("Web callout request failed", {+ projectId: input.projectId,+ endpointId: endpoint.id,+ error: error instanceof Error ? error.message : "Unknown error",});- }-- return {- success: true as const,- status: response.status,- };- } catch (error) {- if (error instanceof TRPCError) {- throw error;- }- logger.warn("Web callout request failed", {- projectId: input.projectId,- endpointId: endpoint.id,- error: error instanceof Error ? error.message : "Unknown error",- });+ if (abortController.signal.aborted) {+ recordWebCalloutInvokeMetric("timed_out", limitContext);+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Web callout timed out after 5 seconds.",+ });+ }- if (abortController.signal.aborted) {+ recordWebCalloutInvokeMetric("failed", limitContext);throw new TRPCError({code: "BAD_REQUEST",- message: "Web callout timed out after 5 seconds.",+ message: "Web callout request failed.",});+ } finally {+ clearTimeout(timeout);}-- throw new TRPCError({- code: "BAD_REQUEST",- message: "Web callout request failed.",- });- } finally {- clearTimeout(timeout);- }+ });};const discardResponseBody = async (response: Response) => {