Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 18 additions & 22 deletions packages/cli/src/lib/sentry-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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,
Expand All @@ -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(),
Expand Down Expand Up @@ -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"
Expand Down
57 changes: 31 additions & 26 deletions packages/cli/test/lib/objectstore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<FormDataEntryValue[]> {
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 },
]),
);

Expand All @@ -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 () => {
Expand All @@ -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" } },
]),
);

Expand Down Expand Up @@ -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 }),
);

Expand All @@ -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",
Expand All @@ -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(
Expand Down
30 changes: 9 additions & 21 deletions packages/mcp-core/src/api-client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
});
Expand Down
90 changes: 52 additions & 38 deletions packages/toolkit-core/src/sentry-retry.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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: {
Expand All @@ -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<Response> => {
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,
);
});
});
Loading
Loading