Repository navigation
feat(http): Add @sentry/http and move CLI and MCP caching and retries onto it - #2509
Conversation
Add a publishable `@sentry/http` package with the provider-neutral HTTP stack that `@sentry/api`, the CLI, and Junior each carry a copy of: - Freshness and revalidation through http-cache-semantics, with ETag and Last-Modified validators. The caller's `ttlMs` caps the freshness that server headers give unless `maxTtlMs` raises it. - `staleIfError`, which keeps stale entries and serves one when the request throws or the server answers 429 or 5xx, with an `onStale` signal. - `fetchWithCache`, one GET through the cache. A client error drops the entry, and a cache failure is a miss. - A pluggable `CacheStore` (now with `delete`), a byte-budgeted memory store, and identity-scoped HMAC keys compatible with existing entries. - The zstd/brotli body codec, moved from toolkit-core to `@sentry/http/codec`. - Retry decisions and a `fetchWithRetry` loop: backoff with jitter, Retry-After, and idempotency-aware replays with configurable statuses. The CLI's response cache and filesystem store now use it, with Sentry's tiers from `@sentry/api/client` as the TTL and `maxTtlMs: Infinity` so server max-age still wins there. Craft, the release workflow, and the post-merge packaging job publish it like `@sentry/logger`. Refs getsentry/junior#4397 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
📊 MCP Server Token Cost ReportSummary
Per-Tool Breakdown
Note: This measures the static overhead of tool definitions sent to LLM clients with every request. Lower is better. MCP Apps viewsEach
The budget applies to raw bytes, and the view's generator fails over it. |
`@sentry/api` stays free of dependencies, so its consumers bring their own retries. `withRetry(fetch, options)` runs the `fetchWithRetry` loop around any fetch-shaped call. It clones a `Request` input and reads a stream body once for each attempt, and it stops at once on the caller's abort. `@sentry/toolkit-core/sentry-retry` adds `withSentryRetry(transport)`, which wraps `@sentry/api`'s transport with Sentry's rules: a 429 replays any method, 5xx replays only idempotent requests, and waits come from `parseRetryDelayMs`. Each attempt is a whole `transport.request`, so it keeps the transport's timeout, body buffering, and credential refresh. The CLI and MCP transports now send each request once (`TRANSPORT_SENDS_ONCE`), and the CLI throws `RateLimitError` itself for a 429 it does not retry. Also fixes three cache bugs found in review: - A lookup whose request differs in a `Vary` header is a miss, with or without server directives, and is never served as stale. - Cached 204, 205, and 304 responses are rebuilt with a null body. - `storeResponse` cancels a body it does not store. Refs getsentry/junior#4397
- Lowercase request header names before policy checks, as http-cache-semantics stores them, so `Vary` matches mixed-case `requestHeaders`. - `withRetry` buffers a `ReadableStream` `init.body` even when the input is a `Request`, so a retry does not resend a used stream.
Only `max-age`, `no-cache`, and `Expires` count as server freshness. A response with only storage directives, such as `Cache-Control: private`, now stays fresh for the caller's `ttlMs` instead of being dropped or always stale.
BYK
left a comment
There was a problem hiding this comment.
License: FSL-1.1-Apache-2.0, matching the @sentry/api and toolkit code it came from. @sentry/logger is MIT.
If there's nothing Sentry-specific here I'd make this MIT or Apache-2.0
First version should be 1.0 as the interface is already battle-tested?
Freshness default: a host that does not raise maxTtlMs no longer lets a server max-age outlast its TTL. The CLI keeps the old behavior with maxTtlMs: Infinity.
Not sure what you mean by this?
- `.craft.yml` declares the standalone libraries once, as the
`packages/{http,logger}` workspace key.
- `merge-jobs.yml` lists the Craft workspaces that use the default
artifact provider (`scripts/npm-library-workspaces.mjs`), packs each
in a parallel matrix job, and merges the tarballs into the artifact
named after the commit. It runs on every release branch but the CLI's.
- `release.yml` takes any directory under `packages/` as the product and
passes it to Craft, which rejects names that are not workspaces.
Publishing another package now needs only its name in `.craft.yml`.
Also releases `@sentry/http` under MIT, with 1.0.0 as its first version.
|
Thanks. All three are in 1227efd6:
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 1227efd. Configure here.
The workflow-level `contents: read` dropped `checks: write`, which `mikepenz/action-junit-report` needs to create its check run.
Server `max-age`, `no-cache`, and `Expires` now decide freshness, longer or shorter than `ttlMs`, as in standard HTTP caching: if the server says a response is good for longer, a refresh would most likely return the same response. `ttlMs` applies when the server sends none. `maxTtlMs` stays as an opt-in hard ceiling for callers that learn of changes another way, such as webhook invalidation with `ttlMs: 0`. The CLI drops its `maxTtlMs: Infinity`, which is now the default. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
- `test.yml` now also runs on release branches, so every release commit gets the per-project matrix. `merge-jobs.yml` drops its own lint and test job and only discovers, packs, and archives the libraries, on every release branch. - `release.yml` keeps `product` as a choice. GitHub cannot fill it from `.craft.yml`, so `workflow-policy.test.mjs` fails when the options and the `packages/` workspaces differ. - `actions/*` steps in `merge-jobs.yml` use floating major tags again.
…i/client (#132687) **Breaking change: this needs a major release (3.0.0).** `@sentry/api` stops shipping a generic HTTP cache and retry policy. The host that consumes it now owns both and plugs them into the transport: the `cache` option (`TransportCache`) and a new `retry` hook. The toolkit CLI and MCP already work this way through `@sentry/http` since getsentry/toolkit#2509. `@sentry/api` gains no new dependency, and `http-cache-semantics` goes away. ### Removed from `@sentry/api/client` - **Cache:** `lookupResponse`, `storeResponse`, `buildCacheKey`, `normalizeUrl`, `createMemoryStore`, `REVALIDATION_WINDOW_MS`, plus the types `CacheStore`, `CacheEntry`, `BodyCodec`, `BodyEncoding`, `EncodedBody`, `MemoryStore`, `MemoryStoreOptions`, `LookupOptions` and `StoreOptions`. - **Retry:** `nextRetryDelayMs`, `sleep` and `RetryPolicy`. - **Transport option:** `retry` changes from a `RetryPolicy` object to an optional hook. ### Retry hook ```ts type TransportRetry = ( attempt: () => Promise<Response>, request: { method: string; url: string; idempotent: boolean; signal: AbortSignal | undefined }, ) => Promise<Response>; ``` The transport calls `retry` once per request, after the cache lookup and the credential's lookup and `prepare`, and inside the host span. The hook calls `attempt()` as often as its policy allows and returns the final response. Each `attempt()` sends once with the transport's timeout, body buffering, redirect checks, and 401 refresh. That refresh replay happens inside the attempt, so it never counts as a retry. It resolves with the response, failed or not. Otherwise it throws: `ApiTimeoutError` when the transport's own timeout fired, the caller's abort reason, the host's `errors.fatal` or redirect-rejection error, or what the fetch threw. The cache store, write invalidation, `errors.rateLimited`, and `errors.timeout` apply once, to what the hook returns or throws. Without the hook, each request is sent once. The hook owns the loop and the wait, so `@sentry/api` has no retry policy, loop, or `@sentry/http` dependency. `@sentry/http`'s `fetchWithRetry(send, options)` implements it directly: ```ts retry: (attempt, { method, idempotent, signal }) => fetchWithRetry(attempt, { policy, method, idempotent, ...(signal ? { signal } : {}), retryableStatuses: SENTRY_RETRYABLE_STATUSES, serverDelayMs: (r) => parseRetryDelayMs(r.status, r.headers), }), ``` ### Kept These are plain data and functions, and none of them depends on `@sentry/http`: - The `TransportCache` seam. `CacheLookup` is now defined in `transport.ts`. - Credential refresh and trusted-origin redirects. - `classifyUrl`, `FALLBACK_TTL_MS`, `TtlTier` and `computeInvalidationPrefixes`. - `parseRetryDelayMs`, which moved to `rate-limit.ts`. It still reads `Retry-After` and `X-Sentry-Rate-Limit-Reset`, and the transport still passes its value to `errors.rateLimited`. - `isIdempotentRequest`, which moved to `idempotent-operations.ts`, plus `selectIdempotentWrites` and `createIdempotentOperationMatcher`. ### Migration - Replace `retry: policy` with a `retry` hook. With `@sentry/http`, wrap `fetchWithRetry` as shown above. - To keep caching, implement `TransportCache` on a cache of your own. ### Toolkit follow-up, after 3.0.0 is published - toolkit-core builds the `retry` hook on `@sentry/http`'s `fetchWithRetry`, with `SENTRY_RETRYABLE_STATUSES` and `parseRetryDelayMs`, and passes it to `createApiTransport`. - `withSentryRetry` stops wrapping `transport.request`, and its outer wrapping goes away. - Delete `TRANSPORT_SENDS_ONCE` and the `retry:` lines that use it in the CLI's `sentry-client.ts` and MCP's `api-client/client.ts`. - `@sentry/http` needs no new export, since `fetchWithRetry` already matches the hook. A named adapter, such as `retryHook(options)`, is optional sugar. ### Breaking changes may remove exports `test/consumers/exports.mjs` now allows removed exports when the change is marked breaking: `type(scope)!:` in the PR title, or a `BREAKING CHANGE:` footer. That's the signal Craft reads to pick a major bump. The script reads the PR title, or the commit message after merge or in the merge queue, from the run's GitHub event, so no workflow changes. The script still lists the removals, and any change not marked breaking still fails. ### Release `openapi.yml`'s automatic release should publish this as 3.0.0 after merge. If a spec change lands before that release runs, its preflight forces a `minor` bump and this would ship as 2.x instead. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A672bf07a67118adf395d2ead4a7cd9aa --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A672bf07a67118adf395d2ead4a7cd9aa) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A672bf07a67118adf395d2ead4a7cd9aa/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <burak.kaya@sentry.io> Co-authored-by: BYK <126780+BYK@users.noreply.github.com>

@sentry/api/client, the CLI, and Junior (getsentry/junior#4393) each carry their own HTTP cache and retry code. This adds one publishable, provider-neutral package,@sentry/http, and plugs it into@sentry/apifrom the toolkit side.@sentry/apigets no new dependency: it keeps its injection points and its Sentry-specific rules, and a follow-up in getsentry/sentry removes its generic cache and retry code. This is step 1 of getsentry/junior#4397.Package
packages/http, published as@sentry/http(free on npm). It is set up like@sentry/logger: the workspace exportssrc/,publishConfig.exportspoints at the tsdown ESM and CJS build, andtest:packagepacks the tarball and type-checks and runs it with TypeScript 5 and 7.@sentry/httpuses no Node APIs, so it runs in Node 22+, Workers, and browsers.@sentry/http/codecis the zstd level 3 / brotli body codec, moved from@sentry/toolkit-core/response-cache/codec. It skips bodies under 256 B and never decompresses past the recorded size.Cache
CacheStorehasget,set(key, entry, ttlMs),delete, anddeleteMatching(identity, urlPrefix).createMemoryStoreis a byte-budgeted LRU.FreshnessOptionsis{ ttlMs, maxTtlMs?, retainMs?, staleIfError? }, passed on each call instead of stored as a tier.max-age,no-cache,Expires) win, longer or shorter.ttlMsapplies when the server sends none, andmaxTtlMsis an optional hard ceiling.Varyheaders. Any other request is a miss.ETagandLast-Modifiedboth count as validators. A stale entry is kept forretainMs(24 h by default) when it has one, or always withstaleIfError.lookupResponseandstoreResponseare for hosts that own their request loop, as@sentry/api'sTransportCacheseam does.stalelookup hascreatedAt, and withstaleIfErrorit also hasserveStale().storeResponsecaches any body.requireJsonkeeps the old JSON-only check.fetchWithCache({ store, codec, identity, url, ttlMs, send, onStale, onCacheError, ... })sends one GET through the cache:staleIfError, a throw, 429, or 5xx serves the stale entry and callsonStale(createdAt)buildCacheKeyis unchanged, so keys from existing entries still match.Retries
nextRetryDelayMs,isIdempotentRequest,parseRetryAfterMs,serverDelayUntil, andsleep.RetryableStatusesis configurable. By default 429 and 5xx replay only idempotent requests.fetchWithRetry(send, options)is the loop.withRetry(fetch, options)wraps any fetch-shaped call with that loop.policy,retryableStatuses,serverDelayMs,isRetryableError,idempotent,isIdempotent({ method, url }),onRetry.Requestinput and reads a stream body once, so each attempt can resend it. An abort from the caller's signal stops it at once.Plugging it into
@sentry/apicacheseam (TransportCache), now backed by@sentry/http'slookupResponse,storeResponse, and keys. A cache entry needs the credential identity the transport resolves, so the seam is the right place for it.fetchoption.@sentry/toolkit-core/sentry-retryexportswithSentryRetry(transport, options), which applies Sentry's rules. A 429 replays any method, since Sentry rejects it before the view runs. A 5xx replays only idempotent requests. Waits come from@sentry/api'sparseRetryDelayMs.transport.request. So it keeps the transport's own timeout, its body buffering (which the CLI chooses per SDKRequest), and the 401 credential refresh.TRANSPORT_SENDS_ONCE. That constant goes away once@sentry/apino longer requiresretry.RateLimitErroritself for a 429 it does not retry.@sentry/api.classifyUrlandFALLBACK_TTL_MS(passed asttlMs; Sentry'smax-agestill wins),computeInvalidationPrefixes,parseRetryDelayMs, and the idempotent-operations matcher are all still imported from@sentry/api/client.With this merged, toolkit no longer uses
@sentry/api's generic response cache (CacheLookup,CacheEntry,CacheStore, the memory store,lookupResponse/storeResponse, keys), its built-in retries, or itserrors.rateLimitedhook.Other toolkit changes
toolkit-coredropsresponse-cache/codec. Its test moved with the code..craft.ymlhas onepackages/{http,logger}workspace for the standalone libraries (<name>@tags,release/<name>/branches, npm target).merge-jobs.ymllists the Craft workspaces that use the default artifact provider (scripts/npm-library-workspaces.mjs). It packs each one in a parallel matrix job and merges the tarballs into the artifact named after the commit. It runs onmainand every release branch, and no longer runs its own lint and tests.test.ymlnow also runs on release branches, so each release commit gets the full per-project matrix.release.ymlkeepsproductas a choice. GitHub can't fill it from.craft.yml, soworkflow-policy.test.mjsfails when the options and thepackages/workspaces differ..craft.ymlkey and to theproductoptions. No other workflow edits are needed.@sentry/mcp-server, all built bycli-build.yml.@sentry/httpis MIT licensed, and its first release is1.0.0.Freshness default
As in standard HTTP caching and in
@sentry/apitoday, a servermax-agecan keep an entry fresh past the caller'sttlMs: if the server says a response is good for longer, a refresh would most likely return the same response. The CLI needs no option for this.maxTtlMsis an opt-in hard ceiling for callers that learn of changes another way. Junior's GitHub reads are the known case: they usettlMs: 0with webhook invalidation, so they passmaxTtlMs: 0to keep a servermax-agefrom skipping the revalidation that picks up a change.Next: getsentry/sentry removes the generic response-cache and retry code from
@sentry/apiand makesretryoptional, as a breaking change.via @BYK.
--
View Session [Sentry]