From c87deb96c8119bf901432f521cbd16422981691d Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:37:32 +0000 Subject: [PATCH 1/2] ref(http): Retry Sentry API requests through @sentry/api 3's retry hook @sentry/api 3.0.0 replaces the transport's `retry` policy with a hook the transport calls once per request, after the cache lookup and the credential's `prepare`. toolkit-core now builds that hook on @sentry/http's `fetchWithRetry` as `sentryRetry`, and the CLI and MCP pass it to `createApiTransport` instead of wrapping `transport.request` with `withSentryRetry`. So a retried request looks up the cache and the credential once, not once per attempt. `TRANSPORT_SENDS_ONCE` goes away. The CLI's `isRetryableError` drops its `TimeoutError` case: an attempt now throws the transport's `ApiTimeoutError`, and `errors.timeout` maps it to `TimeoutError` once, after the hook gives up. The bump also types `event_id` as a string, so the MCP client's cast for 32-character event IDs is no longer needed. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/sentry-client.ts | 40 ++++----- packages/mcp-core/src/api-client/client.ts | 30 ++----- .../toolkit-core/src/sentry-retry.test.ts | 90 +++++++++++-------- packages/toolkit-core/src/sentry-retry.ts | 80 +++++++---------- pnpm-lock.yaml | 17 ++-- pnpm-workspace.yaml | 4 +- 6 files changed, 122 insertions(+), 139 deletions(-) diff --git a/packages/cli/src/lib/sentry-client.ts b/packages/cli/src/lib/sentry-client.ts index 2188387c5..316993115 100644 --- a/packages/cli/src/lib/sentry-client.ts +++ b/packages/cli/src/lib/sentry-client.ts @@ -21,10 +21,7 @@ import { type TransportCache, } from "@sentry/api/client"; import type { RetryPolicy } from "@sentry/http"; -import { - TRANSPORT_SENDS_ONCE, - withSentryRetry, -} from "@sentry/toolkit-core/sentry-retry"; +import { sentryRetry } from "@sentry/toolkit-core/sentry-retry"; import { sentry } from "./app-identity.js"; import { formatAuthHeader } from "./auth-header.js"; import { seedCompletions } from "./api/completion-seed.js"; @@ -314,12 +311,13 @@ const responseCache: TransportCache = { }; /** - * Whether a failed attempt may be sent again: a timeout, or a network or - * body error. CLI errors, such as a TLS failure, a host-scope rejection, or - * an auth error, will not change on a retry. + * Whether a failed attempt may be sent again: a timeout (the transport's + * `ApiTimeoutError`, mapped to {@link TimeoutError} only after the last + * attempt), or a network or body error. CLI errors, such as a TLS failure, a + * host-scope rejection, or an auth error, will not change on a retry. */ function isRetryableError(error: unknown): boolean { - return error instanceof TimeoutError || !(error instanceof CliError); + return !(error instanceof CliError); } /** Wrap a request in an `http.client` span when the CLI traces HTTP by hand. */ @@ -370,8 +368,8 @@ function selectAccountForRequest({ url, scope }: CredentialRequest): void { /** * The CLI's transport options: stored credentials, host-scope checks, the * response cache, and the CLI's error classes. Timeouts, the 401 refresh, - * and redirect validation are in `@sentry/api/client`. The transport sends - * each request once; {@link createAuthenticatedFetch} retries around it. + * and redirect validation are in `@sentry/api/client`. The transport retries + * each attempt through {@link sentryRetry}. */ function createCliTransport({ credential, @@ -397,7 +395,14 @@ function createCliTransport({ refresh: refreshAfterUnauthorized, authorization: (current) => formatAuthHeader(current.token), }, - retry: TRANSPORT_SENDS_ONCE, + retry: sentryRetry({ + policy: RETRY_POLICY, + isRetryableError, + onRetry: ({ attempt, delayMs }, { method, url }) => + log.debug( + `${method} ${extractUrlPath(url)} → retry ${attempt + 1}/${RETRY_POLICY.maxRetries} after ${Math.round(delayMs)}ms`, + ), + }), timeoutMs: timeoutMs ?? resolveTimeoutMs, fetch: (input, init) => fetchWithCustomTls(input, init, dispatcher), userAgent: getUserAgent(), @@ -498,19 +503,10 @@ function createAuthenticatedFetch( const method = init?.method ?? (input instanceof Request ? input.method : "GET"); const path = extractUrlPath(input); - const retrying = withSentryRetry(transport, { - policy: RETRY_POLICY, - isIdempotent: ({ method: m, url }) => isIdempotentOperation(m, url), - isRetryableError, - onRetry: ({ attempt, delayMs }) => - log.debug( - `${method} ${path} → retry ${attempt + 1}/${RETRY_POLICY.maxRetries} after ${Math.round(delayMs)}ms`, - ), - }); - const response = await retrying.request(input, init, { + const response = await transport.request(input, init, { validateRedirects: options.validatedRedirects === true, idempotent: options.idempotent === true, - // Read before the retry clones `input`: the mode is keyed by the SDK's Request. + // Keyed by the SDK's Request, so read from `input` itself. responseBody: method.toUpperCase() !== "GET" ? "stream" diff --git a/packages/mcp-core/src/api-client/client.ts b/packages/mcp-core/src/api-client/client.ts index 115bb413f..195e9b420 100644 --- a/packages/mcp-core/src/api-client/client.ts +++ b/packages/mcp-core/src/api-client/client.ts @@ -3,12 +3,8 @@ import { isAggregateFieldOrEquation, } from "@sentry/toolkit-core/events-fields"; import type { RetryPolicy } from "@sentry/http"; +import { sentryRetry } from "@sentry/toolkit-core/sentry-retry"; import { - TRANSPORT_SENDS_ONCE, - withSentryRetry, -} from "@sentry/toolkit-core/sentry-retry"; -import { - type GetOrganizationIssueEventData, getOrganizationIssue, getOrganizationIssueAutofixState, getOrganizationIssueEvent, @@ -364,23 +360,17 @@ const isIdempotentOperation = createIdempotentOperationMatcher(() => ); /** - * Every request goes through the shared transport, which sends it once; - * `withSentryRetry` retries around it. `SentryApiService` sets its own + * Every request goes through the shared transport, which retries each + * attempt through `sentryRetry`. `SentryApiService` sets its own * headers, including Authorization, and as before there is no timeout. * `fresh` passes on a tool call's `fresh: true`, for when the transport gets * a cache. */ -const transport = withSentryRetry( - createApiTransport({ - retry: TRANSPORT_SENDS_ONCE, - fresh: isFreshRead, - isIdempotent: isIdempotentOperation, - }), - { - policy: REQUEST_RETRY_POLICY, - isIdempotent: ({ method, url }) => isIdempotentOperation(method, url), - }, -); +const transport = createApiTransport({ + retry: sentryRetry({ policy: REQUEST_RETRY_POLICY }), + fresh: isFreshRead, + isIdempotent: isIdempotentOperation, +}); /** * Default cap for returning attachment bytes inline over the MCP transport. @@ -3861,9 +3851,7 @@ export class SentryApiService { path: { organization_id_or_slug: organizationSlug, issue_id: issueId, - // The generated type lists only the aliases, but Sentry also accepts - // a 32-character event ID here. - event_id: eventId as GetOrganizationIssueEventData["path"]["event_id"], + event_id: eventId, }, throwOnError: true, }); diff --git a/packages/toolkit-core/src/sentry-retry.test.ts b/packages/toolkit-core/src/sentry-retry.test.ts index b915beb7d..8b05db6cc 100644 --- a/packages/toolkit-core/src/sentry-retry.test.ts +++ b/packages/toolkit-core/src/sentry-retry.test.ts @@ -1,7 +1,6 @@ +import type { RetryRequest } from "@sentry/api/client"; import { describe, expect, it, vi } from "vitest"; -import { withSentryRetry } from "./sentry-retry"; - -const URL_ = "https://us.sentry.io/api/0/organizations/acme/issues/"; +import { sentryRetry } from "./sentry-retry"; const policy = { maxRetries: 2, @@ -10,9 +9,18 @@ const policy = { maxTotalDelayMs: 1000, }; +function request(method: string, idempotent = false): RetryRequest { + return { + method, + url: "https://us.sentry.io/api/0/organizations/acme/issues/", + idempotent, + signal: undefined, + }; +} + function answering(...statuses: number[]) { return vi.fn( - async (_input: Request | string | URL, _init?: RequestInit) => + async () => new Response(null, { status: statuses.shift() ?? 200, headers: { @@ -23,55 +31,61 @@ function answering(...statuses: number[]) { ); } -describe("withSentryRetry", () => { +describe("sentryRetry", () => { it("replays a rate-limited write, since Sentry rejects it before the view runs", async () => { - const request = answering(429); + const attempt = answering(429); - const response = await withSentryRetry({ request }, { policy }).request( - URL_, - { - method: "POST", - }, - ); + const response = await sentryRetry({ policy })(attempt, request("POST")); expect(response.status).toBe(200); - expect(request).toHaveBeenCalledTimes(2); + expect(attempt).toHaveBeenCalledTimes(2); }); it("does not replay a write after a 5xx", async () => { - const request = answering(503); + const attempt = answering(503); - const response = await withSentryRetry({ request }, { policy }).request( - URL_, - { - method: "PUT", - }, - ); + const response = await sentryRetry({ policy })(attempt, request("PUT")); expect(response.status).toBe(503); - expect(request).toHaveBeenCalledTimes(1); + expect(attempt).toHaveBeenCalledTimes(1); }); - it("replays a write the request marks idempotent, and passes its options on", async () => { - const request = vi.fn( - async ( - _input: Request | string | URL, - _init?: RequestInit, - _options?: { idempotent?: boolean }, - ) => - new Response(null, { - status: request.mock.calls.length === 1 ? 503 : 200, - }), - ); + it("replays a write the transport marks idempotent", async () => { + const attempt = answering(503); - const response = await withSentryRetry({ request }, { policy }).request( - URL_, - { method: "PUT" }, - { idempotent: true }, + const response = await sentryRetry({ policy })( + attempt, + request("PUT", true), ); expect(response.status).toBe(200); - expect(request).toHaveBeenCalledTimes(2); - expect(request.mock.calls[1]?.[2]).toEqual({ idempotent: true }); + expect(attempt).toHaveBeenCalledTimes(2); + }); + + it("does not retry an error the host calls permanent", async () => { + const error = new Error("certificate has expired"); + const attempt = vi.fn(async (): Promise => { + throw error; + }); + + await expect( + sentryRetry({ policy, isRetryableError: (e) => e !== error })( + attempt, + request("GET"), + ), + ).rejects.toBe(error); + expect(attempt).toHaveBeenCalledTimes(1); + }); + + it("tells onRetry which request it retries", async () => { + const onRetry = vi.fn(); + const get = request("GET"); + + await sentryRetry({ policy, onRetry })(answering(502), get); + + expect(onRetry).toHaveBeenCalledWith( + expect.objectContaining({ attempt: 0, status: 502 }), + get, + ); }); }); diff --git a/packages/toolkit-core/src/sentry-retry.ts b/packages/toolkit-core/src/sentry-retry.ts index 6b8c34b22..fd8d996fd 100644 --- a/packages/toolkit-core/src/sentry-retry.ts +++ b/packages/toolkit-core/src/sentry-retry.ts @@ -1,18 +1,20 @@ /** * Retries for Sentry API requests, shared by the CLI and MCP. `@sentry/api` - * sends each request once; the host wraps its transport with these so the - * retry policy stays the host's choice. + * sends each request once unless the host passes a `retry` hook; this + * builds that hook on `@sentry/http`, so the retry policy stays the host's + * choice. */ import { - type ApiTransport, parseRetryDelayMs, - type RetryPolicy, + type RetryRequest, + type TransportRetry, } from "@sentry/api/client"; import { + fetchWithRetry, type RetryableStatuses, - type RetryingFetchOptions, - withRetry, + type RetryAttempt, + type RetryOptions, } from "@sentry/http"; /** @@ -30,49 +32,33 @@ export const SENTRY_RETRYABLE_STATUSES: RetryableStatuses = new Map([ [504, "idempotent"], ]); -/** - * The transport's own retry policy: none, since {@link withSentryRetry} - * retries around it. Remove once `@sentry/api` drops the required `retry`. - */ -export const TRANSPORT_SENDS_ONCE: RetryPolicy = { - maxRetries: 0, - baseDelayMs: 0, - maxDelayMs: 0, - maxTotalDelayMs: 0, +/** Options for {@link sentryRetry}; the statuses and delays are Sentry's. */ +export type SentryRetryOptions = Pick< + RetryOptions, + "policy" | "isRetryableError" +> & { + onRetry?: (retry: RetryAttempt, request: RetryRequest) => void; }; -/** Options for {@link withSentryRetry}; the statuses and delays are Sentry's. */ -export type SentryRetryOptions = Omit< - RetryingFetchOptions, - "retryableStatuses" | "serverDelayMs" ->; - /** - * Wrap `transport` so a failed Sentry API request is sent again, waiting - * for `Retry-After` or Sentry's rate-limit reset when the response gives - * one. Each attempt is a whole `transport.request` call, so it keeps the - * transport's timeout, body handling, and credential refresh. + * The transport's `retry` hook: send a failed Sentry API request again, + * waiting for `Retry-After` or Sentry's rate-limit reset when the response + * gives one. The transport looks up the cache and the credential once per + * request; each attempt keeps its timeout, body handling, and 401 refresh. */ -export function withSentryRetry( - transport: ApiTransport, - options: SentryRetryOptions, -): ApiTransport { - const request: ApiTransport["request"] = async ( - input, - init, - requestOptions, - ) => - await withRetry( - async (attemptInput, attemptInit) => - await transport.request(attemptInput, attemptInit, requestOptions), - { - ...options, - idempotent: - options.idempotent === true || requestOptions?.idempotent === true, - retryableStatuses: SENTRY_RETRYABLE_STATUSES, - serverDelayMs: (response) => - parseRetryDelayMs(response.status, response.headers), - }, - )(input, init); - return { request }; +export function sentryRetry({ + onRetry, + ...options +}: SentryRetryOptions): TransportRetry { + return async (attempt, request) => + await fetchWithRetry(attempt, { + ...options, + method: request.method, + idempotent: request.idempotent, + ...(request.signal ? { signal: request.signal } : {}), + retryableStatuses: SENTRY_RETRYABLE_STATUSES, + serverDelayMs: (response) => + parseRetryDelayMs(response.status, response.headers), + ...(onRetry ? { onRetry: (retry) => onRetry(retry, request) } : {}), + }); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6ee44aa18..32dd34a72 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -214,8 +214,8 @@ catalogs: specifier: ^1.2.3 version: 1.2.3 '@sentry/api': - specifier: 2.15.0 - version: 2.15.0 + specifier: 3.0.0 + version: 3.0.0 '@sentry/cloudflare': specifier: 11.12.0 version: 11.12.0 @@ -701,7 +701,7 @@ importers: version: 2.1.7(hono@4.13.18) '@sentry/api': specifier: 'catalog:' - version: 2.15.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) + version: 3.0.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) '@sentry/core': specifier: 'catalog:' version: 11.12.0 @@ -1066,7 +1066,7 @@ importers: version: 2.4.0 '@sentry/api': specifier: 'catalog:' - version: 2.15.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) + version: 3.0.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) '@sentry/core': specifier: 'catalog:' version: 11.12.0 @@ -1253,7 +1253,7 @@ importers: dependencies: '@sentry/api': specifier: 'catalog:' - version: 2.15.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) + version: 3.0.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) '@sentry/http': specifier: workspace:* version: link:../http @@ -4453,8 +4453,8 @@ packages: cpu: [x64] os: [win32] - '@sentry/api@2.15.0': - resolution: {integrity: sha512-y/i2vNAYCFELvHC0n+c8BmCG3nId2UKWEA0w0VDc6iXJZCFDRu2eZ6M5a0/shUVOEvMo6ktan1wXrnJLZTcS8A==} + '@sentry/api@3.0.0': + resolution: {integrity: sha512-bb4mGHF2PWf8yhxiUipGHcDHWRhmHxlbniuX2dO6Wjg0PvqGA+2DXQmM3Rwq36t3mr9Cp1La0q1IY48crvnTuA==} engines: {node: '>=22'} peerDependencies: valibot: '*' @@ -11497,9 +11497,8 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.62.4': optional: true - '@sentry/api@2.15.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7)': + '@sentry/api@3.0.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7)': dependencies: - http-cache-semantics: 4.3.0 p-limit: 7.3.3 typescript: '@typescript/typescript6@6.0.2' optionalDependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 51d7f42ef..cc9f70ae7 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -63,7 +63,7 @@ catalog: "@modelcontextprotocol/server": 2.4.0 "@radix-ui/react-accordion": ^1.2.20 "@radix-ui/react-slot": ^1.2.3 - "@sentry/api": 2.15.0 + "@sentry/api": 3.0.0 "@sentry/cloudflare": 11.12.0 "@sentry/core": 11.12.0 "@sentry/node": 11.12.0 @@ -154,7 +154,7 @@ minimumReleaseAgeExclude: - "@sentry/search-syntax@1.0.0" - "@sentry/server-runtime-injection@11.12.0" - "@sentry/server-utils@11.12.0" - - "@sentry/api@2.15.0" + - "@sentry/api@3.0.0" - miniflare@5.20261101.0-beta - wrangler@4.156.1 - "@sentry/symbolic@14.0.0-alpha.5" From 3c1ffdf966000a83ef4a52608d1e8557d072df9e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:49:03 +0000 Subject: [PATCH 2/2] test(cli): Build Objectstore batch fixtures in @sentry/api 3's format @sentry/api 3.0.0 includes getsentry/sentry#131779, which sends and reads Objectstore batches as FormData: one JSON part per operation, named by its index, with an insert's bytes in `.payload`. The CLI's objectstore tests still built responses with the old `x-sn-batch-operation-*` part headers, which the new parser rejects. --- packages/cli/test/lib/objectstore.test.ts | 57 ++++++++++++----------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/packages/cli/test/lib/objectstore.test.ts b/packages/cli/test/lib/objectstore.test.ts index f6c5037f4..41f9a12d2 100644 --- a/packages/cli/test/lib/objectstore.test.ts +++ b/packages/cli/test/lib/objectstore.test.ts @@ -42,43 +42,43 @@ afterEach(() => { vi.restoreAllMocks(); }); -/** Build a batch response in the server's `multipart/form-data` shape. */ +/** + * Build a batch response in the server's layout: one JSON part per + * operation, named by its index. + */ function batchResponse( - parts: { index: number; status: string; body?: string }[], + parts: { index: number; status: number; error?: { detail?: string } }[], ): Response { const boundary = "os-boundary-00000000000000000000000000000abc"; let text = ""; - for (const part of parts) { + for (const { index, ...result } of parts) { text += `--${boundary}\r\n` + - `x-sn-batch-operation-index: ${part.index}\r\n` + - `x-sn-batch-operation-status: ${part.status}\r\n` + - "content-disposition: form-data; name=part\r\n\r\n" + - `${part.body ?? ""}\r\n`; + `content-disposition: form-data; name="${index}"\r\n` + + "content-type: application/json\r\n\r\n" + + `${JSON.stringify(result)}\r\n`; } - text += `--${boundary}--`; + text += `--${boundary}--\r\n`; return new Response(text, { status: 200, headers: { "content-type": `multipart/form-data; boundary="${boundary}"` }, }); } -/** Decode a captured batch request body as multipart form data. */ -async function sentParts(init: RequestInit): Promise { - const headers = new Headers(init.headers); - const form = await new Response(init.body as BodyInit, { - headers: { "content-type": headers.get("content-type") as string }, - }).formData(); - return form.getAll("part"); +/** The operations a captured batch request sends, one per index-named part. */ +function sentOperations(init: RequestInit): unknown[] { + return [...(init.body as FormData)] + .filter(([name]) => /^\d+$/.test(name)) + .map(([, value]) => JSON.parse(value as string)); } describe("findExistingObjects", () => { test("sends HEADs as one batch through customFetch", async () => { customFetchMock.mockResolvedValue( batchResponse([ - { index: 1, status: "404 Not Found" }, - { index: 0, status: "200 OK" }, - { index: 2, status: "200 OK" }, + { index: 1, status: 404 }, + { index: 0, status: 200 }, + { index: 2, status: 200 }, ]), ); @@ -90,7 +90,11 @@ describe("findExistingObjects", () => { expect(url).toBe(BATCH_URL); expect(init.method).toBe("POST"); expect(new Headers(init.headers).get("x-os-auth")).toBe("Bearer jwt-token"); - expect(await sentParts(init)).toHaveLength(3); + expect(sentOperations(init)).toEqual([ + { kind: "head", key: "k0" }, + { kind: "head", key: "k1" }, + { kind: "head", key: "k2" }, + ]); }); test("throws a CLI ApiError with the request URL when the batch fails", async () => { @@ -108,8 +112,8 @@ describe("findExistingObjects", () => { test("throws a CLI ApiError for a failed operation inside a batch", async () => { customFetchMock.mockResolvedValue( batchResponse([ - { index: 0, status: "200 OK" }, - { index: 1, status: "429 Too Many Requests", body: "slow down" }, + { index: 0, status: 200 }, + { index: 1, status: 429, error: { detail: "slow down" } }, ]), ); @@ -140,7 +144,7 @@ describe("putObjects", () => { await writeFile(large, new Uint8Array(1024 * 1024 + 1)); customFetchMock.mockImplementation(async (_url, init: RequestInit) => init.method === "POST" - ? batchResponse([{ index: 0, status: "201 Created" }]) + ? batchResponse([{ index: 0, status: 201 }]) : new Response(null, { status: 201 }), ); @@ -154,9 +158,10 @@ describe("putObjects", () => { ([, init]) => init.method === "POST", ) ?? [undefined, undefined]; expect(batchUrl).toBe(BATCH_URL); - const parts = await sentParts(batchInit); - // Parts without a filename decode as strings. - expect(parts).toEqual(["\x01\x02\x03"]); + const payload = (batchInit.body as FormData).get("0.payload") as File; + expect(new Uint8Array(await payload.arrayBuffer())).toEqual( + new Uint8Array([1, 2, 3]), + ); const [putUrl, putInit] = customFetchMock.mock.calls.find( ([, init]) => init.method === "PUT", @@ -171,7 +176,7 @@ describe("putObjects", () => { const small = join(dir, "small.png"); await writeFile(small, new Uint8Array([1])); customFetchMock.mockResolvedValue( - batchResponse([{ index: 0, status: "500 Internal Server Error" }]), + batchResponse([{ index: 0, status: 500 }]), ); const error = await putObjects(config, [{ key: "k", path: small }]).catch(