From 6f6643bf6531576c161a3b31c840b822792d8d15 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:55:22 +0000 Subject: [PATCH 1/8] feat(http): Add @sentry/http for response caching and retries 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> --- .craft.yml | 10 + .github/workflows/merge-jobs.yml | 9 +- .github/workflows/release.yml | 4 + AGENTS.md | 1 + docs/README.md | 4 +- docs/architecture/overview.md | 1 + packages/cli/package.json | 1 + packages/cli/src/lib/response-cache-store.ts | 14 +- packages/cli/src/lib/response-cache.ts | 42 +- .../cli/test/lib/response-cache-store.test.ts | 4 +- packages/http/LICENSE.md | 105 +++++ packages/http/README.md | 138 ++++++ packages/http/package.json | 90 ++++ packages/http/src/body.ts | 55 +++ .../response-cache => http/src}/codec.test.ts | 0 .../src/response-cache => http/src}/codec.ts | 4 +- packages/http/src/fetch.test.ts | 207 +++++++++ packages/http/src/fetch.ts | 179 +++++++ packages/http/src/index.ts | 45 ++ packages/http/src/keys.property.test.ts | 164 +++++++ packages/http/src/keys.test.ts | 64 +++ packages/http/src/keys.ts | 68 +++ packages/http/src/memory-store.test.ts | 250 ++++++++++ packages/http/src/memory-store.ts | 145 ++++++ packages/http/src/policy.test.ts | 434 +++++++++++++++++ packages/http/src/policy.ts | 439 ++++++++++++++++++ packages/http/src/retry.test.ts | 424 +++++++++++++++++ packages/http/src/retry.ts | 307 ++++++++++++ packages/http/src/store.ts | 54 +++ packages/http/test/package/check.sh | 35 ++ packages/http/test/package/consumer/cjs.cts | 8 + packages/http/test/package/consumer/esm.ts | 40 ++ .../http/test/package/consumer/package.json | 4 + .../package/consumer/tsconfig.bundler.json | 11 + .../http/test/package/consumer/tsconfig.json | 14 + packages/http/tsconfig.browser.json | 10 + packages/http/tsconfig.json | 14 + packages/http/tsdown.config.ts | 21 + packages/toolkit-core/README.md | 10 - packages/toolkit-core/package.json | 4 - packages/toolkit-core/tsconfig.browser.json | 2 +- pnpm-lock.yaml | 28 ++ scripts/tsconfig-policy.test.mjs | 5 + 43 files changed, 3420 insertions(+), 48 deletions(-) create mode 100644 packages/http/LICENSE.md create mode 100644 packages/http/README.md create mode 100644 packages/http/package.json create mode 100644 packages/http/src/body.ts rename packages/{toolkit-core/src/response-cache => http/src}/codec.test.ts (100%) rename packages/{toolkit-core/src/response-cache => http/src}/codec.ts (96%) create mode 100644 packages/http/src/fetch.test.ts create mode 100644 packages/http/src/fetch.ts create mode 100644 packages/http/src/index.ts create mode 100644 packages/http/src/keys.property.test.ts create mode 100644 packages/http/src/keys.test.ts create mode 100644 packages/http/src/keys.ts create mode 100644 packages/http/src/memory-store.test.ts create mode 100644 packages/http/src/memory-store.ts create mode 100644 packages/http/src/policy.test.ts create mode 100644 packages/http/src/policy.ts create mode 100644 packages/http/src/retry.test.ts create mode 100644 packages/http/src/retry.ts create mode 100644 packages/http/src/store.ts create mode 100644 packages/http/test/package/check.sh create mode 100644 packages/http/test/package/consumer/cjs.cts create mode 100644 packages/http/test/package/consumer/esm.ts create mode 100644 packages/http/test/package/consumer/package.json create mode 100644 packages/http/test/package/consumer/tsconfig.bundler.json create mode 100644 packages/http/test/package/consumer/tsconfig.json create mode 100644 packages/http/tsconfig.browser.json create mode 100644 packages/http/tsconfig.json create mode 100644 packages/http/tsdown.config.ts diff --git a/.craft.yml b/.craft.yml index 2cda5cb1a1..3fb2501910 100644 --- a/.craft.yml +++ b/.craft.yml @@ -134,6 +134,16 @@ workspaces: end end # No preReleaseCommand: Craft bumps package.json through the npm target. + packages/http: + changelog: + policy: auto + releaseBranchPrefix: "release/{{workspaceName}}" + targets: + - name: github + tagPrefix: "{{workspaceName}}@" + includeNames: '/^{{packageSimpleName}}-\d.*\.tgz$/' + - name: npm + includeNames: '/^{{packageSimpleName}}-\d.*\.tgz$/' packages/logger: changelog: policy: auto diff --git a/.github/workflows/merge-jobs.yml b/.github/workflows/merge-jobs.yml index 5156a9191c..dd6f2f4adb 100644 --- a/.github/workflows/merge-jobs.yml +++ b/.github/workflows/merge-jobs.yml @@ -2,7 +2,7 @@ name: Post-merge tasks on: push: - branches: ["main", "release/*", "release/logger/**"] + branches: ["main", "release/*", "release/http/**", "release/logger/**"] workflow_dispatch: jobs: @@ -26,7 +26,7 @@ jobs: run: pnpm install - name: Build - run: pnpm --filter '@sentry/mcp-core...' --filter @sentry/logger --if-present run build + run: pnpm --filter '@sentry/mcp-core...' --filter @sentry/http --filter @sentry/logger --if-present run build - name: Run linter run: pnpm lint @@ -34,6 +34,10 @@ jobs: - name: Run tests run: pnpm test:ci + - name: Package http + working-directory: packages/http + run: pnpm pack --pack-destination dist + - name: Package logger working-directory: packages/logger run: pnpm pack --pack-destination dist @@ -43,6 +47,7 @@ jobs: with: name: ${{ github.sha }} path: | + ${{ github.workspace }}/packages/http/dist/*.tgz ${{ github.workspace }}/packages/logger/dist/*.tgz - name: Publish Test Report diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4cf8b7c764..23d814a5b3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,6 +10,7 @@ on: default: cli options: - cli + - http - logger bump: description: "Version bump: auto (from commits), pre (next prerelease), or an explicit bump type" @@ -72,6 +73,9 @@ jobs: cli) workspace=packages/cli ;; + http) + workspace=packages/http + ;; logger) workspace=packages/logger ;; diff --git a/AGENTS.md b/AGENTS.md index ee494902c5..5b1a45d4c4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ toolkit/ ├── packages/ │ ├── cli/ # Sentry CLI (see packages/cli/AGENTS.md) │ ├── codemod-cli3to4/ # @getsentry/cli3to4 codemod: CLI v3 → v4 (Codemod Registry) +│ ├── http/ # HTTP response cache, body codec, and retries (@sentry/http on npm) │ ├── logger/ # Structured logger (@sentry/logger on npm) │ ├── toolkit-core/ # Shared CLI/MCP primitives │ ├── mcp-core/ # Core MCP implementation (private) diff --git a/docs/README.md b/docs/README.md index 56865b6332..b083b83110 100644 --- a/docs/README.md +++ b/docs/README.md @@ -35,7 +35,9 @@ For package-specific rules, see the root [AGENTS.md](../AGENTS.md) and the [CLI AGENTS.md](../packages/cli/AGENTS.md). `packages/toolkit-core/` contains shared primitives used by both products. `packages/logger/` is the structured logger the CLI uses, published to npm as `@sentry/logger`; see its -[README](../packages/logger/README.md). +[README](../packages/logger/README.md). `packages/http/` is the HTTP response +cache, body codec, and retry logic, published to npm as `@sentry/http`; see +its [README](../packages/http/README.md). ## Ownership diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index aba641c8f1..6ac61adc24 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -13,6 +13,7 @@ The project is a pnpm monorepo with clear separation of concerns: ``` packages/ ├── cli/ # Sentry CLI, including the `sentry mcp` stdio server +├── http/ # HTTP response cache, body codec, and retries (@sentry/http on npm) ├── toolkit-core/ # Shared CLI/MCP primitives ├── mcp-core/ # Core MCP implementation (private package) ├── mcp-server/ # stdio transport (@sentry/mcp-server on npm) diff --git a/packages/cli/package.json b/packages/cli/package.json index fc2d5ef556..f310e38e1f 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -102,6 +102,7 @@ "@hono/node-server": "^2.1.6", "@sentry/api": "catalog:", "@sentry/core": "catalog:", + "@sentry/http": "workspace:*", "@sentry/logger": "workspace:*", "@sentry/mcp-core": "workspace:*", "@sentry/node": "catalog:", diff --git a/packages/cli/src/lib/response-cache-store.ts b/packages/cli/src/lib/response-cache-store.ts index b4aa74bcde..e20edb9e29 100644 --- a/packages/cli/src/lib/response-cache-store.ts +++ b/packages/cli/src/lib/response-cache-store.ts @@ -2,7 +2,7 @@ * Filesystem {@link CacheStore} for the CLI's response cache. * * Each entry is one JSON file, `.v2.json`, written atomically. Its body - * holds the bytes from the toolkit-core codec (zstd, or brotli on Node < 22.15) + * holds the bytes from the `@sentry/http` codec (zstd, or brotli on Node < 22.15) * as base64. A byte budget over file sizes is enforced by a cleanup sweep that * runs on a share of writes: it deletes expired entries, then evicts the least * recently used ones. A cache hit touches the file's mtime, so mtime is the @@ -30,13 +30,8 @@ import { writeFile, } from "node:fs/promises"; import { join } from "node:path"; -import { - type CacheEntry, - type CacheStore, - classifyUrl, - FALLBACK_TTL_MS, -} from "@sentry/api/client"; -import type { BodyEncoding } from "@sentry/toolkit-core/response-cache/codec"; +import { classifyUrl, FALLBACK_TTL_MS } from "@sentry/api/client"; +import type { BodyEncoding, CacheEntry, CacheStore } from "@sentry/http"; import pLimit from "p-limit"; import { logger } from "./logger.js"; @@ -107,8 +102,6 @@ export type FileStoreOptions = { }; export type FileStore = CacheStore & { - /** Remove the entry under `key`, in either format. */ - delete(key: string): Promise; /** Remove every entry. */ clear(): Promise; /** Delete expired entries, then evict until within the byte budget. */ @@ -199,7 +192,6 @@ function fromLegacy(legacy: LegacyEntry): ParsedEntry { entry: { url: legacy.url, identity: legacy.identity ?? "", - tier: classifyUrl(legacy.url), status: legacy.status, headers: legacy.headers, body: { bytes, encoding: "identity", rawSize: bytes.byteLength }, diff --git a/packages/cli/src/lib/response-cache.ts b/packages/cli/src/lib/response-cache.ts index b87a6350f8..982ae37659 100644 --- a/packages/cli/src/lib/response-cache.ts +++ b/packages/cli/src/lib/response-cache.ts @@ -1,14 +1,14 @@ /** * HTTP response cache for read-only API calls. * - * Freshness, revalidation, and retention come from the shared cache policy - * in `@sentry/api/client` (`lookupResponse` / `storeResponse`): server - * `Cache-Control` / `ETag` / `Expires` headers win, and a URL-based fallback - * TTL applies when the server sends none (Sentry's current behavior). This - * module adds the CLI's store, identity, kill switches, telemetry, and - * cache-age hint. + * Freshness, revalidation, and retention come from the cache policy in + * `@sentry/http` (`lookupResponse` / `storeResponse`): server + * `Cache-Control` / `ETag` / `Expires` headers win, and the URL's fallback + * tier from `@sentry/api/client` applies when the server sends none + * (Sentry's current behavior). This module adds the CLI's store, identity, + * kill switches, telemetry, and cache-age hint. * - * Bodies are compressed with the toolkit-core codec and kept in a + * Bodies are compressed with the `@sentry/http/codec` codec and kept in a * filesystem store under `~/.sentry/cache/api-responses/` (see * `response-cache-store.ts`), separate from the config SQLite database, which * stores small structured data (tokens, org slugs, cursors). @@ -18,14 +18,15 @@ import { rm } from "node:fs/promises"; import { join } from "node:path"; +import { classifyUrl, FALLBACK_TTL_MS } from "@sentry/api/client"; import { - buildCacheKey as buildIdentityCacheKey, type CacheLookup, - classifyUrl, + type FreshnessOptions, + buildCacheKey as buildIdentityCacheKey, lookupResponse, storeResponse, -} from "@sentry/api/client"; -import { createBodyCodec } from "@sentry/toolkit-core/response-cache/codec"; +} from "@sentry/http"; +import { createBodyCodec } from "@sentry/http/codec"; import { getIdentityFingerprint } from "./db/auth.js"; import { getConfigDir } from "./db/index.js"; @@ -38,9 +39,19 @@ import { recordCacheHit, withCacheSpan } from "./telemetry.js"; const log = logger.withTag("response-cache"); // --------------------------------------------------------------------------- -// Cache keys — tiers, keys, and invalidation prefixes live in @sentry/api/client +// Cache keys live in @sentry/http; tiers and invalidation prefixes in +// @sentry/api/client // --------------------------------------------------------------------------- +/** + * Freshness for a Sentry API URL: its fallback tier's TTL when the server + * sends no cache headers. The server's `max-age` may give more, since Sentry + * sets it only on endpoints whose data rarely changes. + */ +function freshness(url: string): FreshnessOptions { + return { ttlMs: FALLBACK_TTL_MS[classifyUrl(url)], maxTtlMs: Infinity }; +} + /** * Build the cache key for the active identity + method + URL. * @@ -190,7 +201,7 @@ export type { CacheLookup }; * Look up a GET request in the cache. * * A fresh entry is a `hit`, and a stale entry with an `ETag` is returned for - * conditional revalidation (see `lookupResponse` in `@sentry/api/client`). + * conditional revalidation (see `lookupResponse` in `@sentry/http`). * * @param method - HTTP method (only "GET" is cached) * @param url - Full request URL @@ -233,6 +244,7 @@ export async function lookupCachedResponse( try { const lookup = await lookupResponse({ + ...freshness(url), store, codec, key, @@ -294,7 +306,7 @@ export async function getCachedResponse( * Store a response in the cache. * * Only caches successful (2xx) GET responses that HTTP caching allows (see - * `storeResponse` in `@sentry/api/client`); `Cache-Control: no-store` is not + * `storeResponse` in `@sentry/http`); `Cache-Control: no-store` is not * cached. * * This function is fire-and-forget — errors are silently swallowed to avoid @@ -338,6 +350,7 @@ export async function storeCachedResponse( "cache.put", async (span) => { const size = await storeResponse({ + ...freshness(url), store, codec, key, @@ -345,6 +358,7 @@ export async function storeCachedResponse( url, requestHeaders, response, + requireJson: true, }); if (size > 0) { span.setAttribute("cache.item_size", size); diff --git a/packages/cli/test/lib/response-cache-store.test.ts b/packages/cli/test/lib/response-cache-store.test.ts index 6820dae569..a032824a63 100644 --- a/packages/cli/test/lib/response-cache-store.test.ts +++ b/packages/cli/test/lib/response-cache-store.test.ts @@ -14,7 +14,7 @@ import { } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import type { CacheEntry } from "@sentry/api/client"; +import type { CacheEntry } from "@sentry/http"; import { afterEach, beforeEach, describe, expect, test } from "vitest"; import { createFileStore, @@ -42,7 +42,6 @@ function entry(path: string, size = 100, identity = "a"): CacheEntry { return { url: `${API}${path}`, identity, - tier: "stable", status: 200, headers: {}, body: { bytes: new Uint8Array(size), encoding: "identity", rawSize: size }, @@ -171,7 +170,6 @@ describe("createFileStore", () => { expect(JSON.parse(Buffer.from(cached!.body.bytes).toString())).toEqual({ id: "old", }); - expect(cached?.tier).toBe("volatile"); }); test("expire by their URL tier when they have no expiresAt", async () => { diff --git a/packages/http/LICENSE.md b/packages/http/LICENSE.md new file mode 100644 index 0000000000..6e9bafc7ac --- /dev/null +++ b/packages/http/LICENSE.md @@ -0,0 +1,105 @@ +# Functional Source License, Version 1.1, Apache 2.0 Future License + +## Abbreviation + +FSL-1.1-Apache-2.0 + +## Notice + +Copyright 2025 Functional Software, Inc. dba Sentry + +## Terms and Conditions + +### Licensor ("We") + +The party offering the Software under these Terms and Conditions. + +### The Software + +The "Software" is each version of the software that we make available under +these Terms and Conditions, as indicated by our inclusion of these Terms and +Conditions with the Software. + +### License Grant + +Subject to your compliance with this License Grant and the Patents, +Redistribution and Trademark clauses below, we hereby grant you the right to +use, copy, modify, create derivative works, publicly perform, publicly display +and redistribute the Software for any Permitted Purpose identified below. + +### Permitted Purpose + +A Permitted Purpose is any purpose other than a Competing Use. A Competing Use +means making the Software available to others in a commercial product or +service that: + +1. substitutes for the Software; + +2. substitutes for any other product or service we offer using the Software + that exists as of the date we make the Software available; or + +3. offers the same or substantially similar functionality as the Software. + +Permitted Purposes specifically include using the Software: + +1. for your internal use and access; + +2. for non-commercial education; + +3. for non-commercial research; and + +4. in connection with professional services that you provide to a licensee + using the Software in accordance with these Terms and Conditions. + +### Patents + +To the extent your use for a Permitted Purpose would necessarily infringe our +patents, the license grant above includes a license under our patents. If you +make a claim against any party that the Software infringes or contributes to +the infringement of any patent, then your patent license to the Software ends +immediately. + +### Redistribution + +The Terms and Conditions apply to all copies, modifications and derivatives of +the Software. + +If you redistribute any copies, modifications or derivatives of the Software, +you must include a copy of or a link to these Terms and Conditions and not +remove any copyright notices provided in or with the Software. + +### Disclaimer + +THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR +PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT. + +IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE +SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, +EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE. + +### Trademarks + +Except for displaying the License Details and identifying us as the origin of +the Software, you have no right under these Terms and Conditions to use our +trademarks, trade names, service marks or product names. + +## Grant of Future License + +We hereby irrevocably grant you an additional license to use the Software under +the Apache License, Version 2.0 that is effective on the second anniversary of +the date we make the Software available. On or after that date, you may use the +Software under the Apache License, Version 2.0, in which case the following +will apply: + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. + +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/packages/http/README.md b/packages/http/README.md new file mode 100644 index 0000000000..0ad45a34de --- /dev/null +++ b/packages/http/README.md @@ -0,0 +1,138 @@ +# @sentry/http + +HTTP response caching, body compression, and retries over the Fetch API. It +runs in Node 22+, Cloudflare Workers, and browsers. The cache backend is yours: +implement `CacheStore` over Redis, SQLite, files, or R2, or use the in-memory +store that ships with the package. + +```sh +npm install @sentry/http +``` + +## Read through the cache + +`fetchWithCache` sends one GET through the cache. A fresh entry serves with no +request. A stale entry is revalidated with its `ETag` or `Last-Modified`, and a +`304 Not Modified` renews it. A 2xx response is stored. A 403, 404, or other +client error drops the entry. + +```ts +import { createMemoryStore, fetchWithCache } from "@sentry/http"; +import { createBodyCodec } from "@sentry/http/codec"; + +const store = createMemoryStore({ maxBytes: 16 * 1024 * 1024 }); +const codec = createBodyCodec(); + +const response = await fetchWithCache({ + store, + codec, + // A stable hash of who is asking, never a raw token. + identity: tokenFingerprint, + url, + ttlMs: 60_000, + staleIfError: true, + onStale: (createdAt) => console.warn(`served data from ${createdAt}`), + send: (validators) => fetch(url, { headers: { ...headers, ...validators } }), +}); +``` + +### Freshness + +- `ttlMs` is how long a response serves without a request. `0` revalidates + every read. +- Server cache headers (`Cache-Control`, `Expires`) can only shorten `ttlMs`, + never extend it, so a server `max-age` cannot make a read skip revalidation + longer than you allow. Set `maxTtlMs` to let the server's headers give more, + such as `Infinity` to follow them. +- A stale entry with a validator stays in the store for `retainMs` (24 hours by + default) so it can be revalidated. +- With `staleIfError`, a stale entry also stays without a validator. When `send` + throws, or the server answers 429 or 5xx, the stale entry is served and + `onStale` gets the time it was stored. + +A cache failure, such as a store that is down or an entry that does not decode, +is a miss. It never fails the request; `onCacheError` reports it. + +### Keys + +`buildCacheKey(method, url, identity)` is the hex HMAC-SHA256 of the method +and the URL, with query parameters sorted, keyed by `identity`. An entry of one +identity never serves another. Pass your own `key` to `fetchWithCache` to add +request parts that change the response, such as `Accept`. + +## Bring your own store + +```ts +import type { CacheEntry, CacheStore } from "@sentry/http"; + +const store: CacheStore = { + async get(key) { + /* the entry, or undefined if missing or expired */ + }, + async set(key, entry: CacheEntry, ttlMs) { + /* keep it for ttlMs; drop the old entry if this one is over your limits */ + }, + async delete(key) {}, + async deleteMatching(identity, urlPrefix) { + /* remove identity's entries whose url starts with urlPrefix */ + }, +}; +``` + +`ttlMs` is how long to keep the entry, not how long it is fresh. Each store +enforces its own byte limits. `entry.body.bytes` is already encoded by the +codec; a store that keeps JSON can save it as base64. `entry.policy` is the +serialized cache policy: store it as is. + +`createMemoryStore()` keeps entries in a byte-budgeted LRU map (24 MiB by +default, 1 MiB per stored body). + +## Body codec + +`@sentry/http/codec` compresses bodies with zstd level 3, or brotli where the +runtime has no zstd (Node before 22.15). Bodies under 256 bytes stay +uncompressed. Decompression never goes past the size recorded at encode time, +and an entry the runtime cannot decode is a miss. It needs `node:zlib`, which +Cloudflare Workers have with `nodejs_compat`. Without it, use `identityCodec`. + +## Lower-level policy + +`lookupResponse` and `storeResponse` are the steps `fetchWithCache` uses, for +hosts that own their request loop. `lookupResponse` returns a `hit` to serve, a +`stale` entry with the `conditionalHeaders` to send and a `revalidate` for the +response, or `undefined` for a miss. + +## Retries + +`fetchWithRetry` sends a request again after a retryable failure: + +```ts +import { fetchWithRetry } from "@sentry/http"; + +const response = await fetchWithRetry(() => fetch(url, { method: "POST" }), { + method: "POST", + policy: { + maxRetries: 2, + baseDelayMs: 250, + maxDelayMs: 5_000, + maxTotalDelayMs: 10_000, + }, +}); +``` + +- It waits for `Retry-After` when the server sends one, otherwise for an + exponential backoff with jitter. It stops when a wait exceeds `maxDelayMs` + or the total would exceed `maxTotalDelayMs`. +- 429, 500, 502, 503, and 504 retry, and so do errors that `send` throws, but + only for GET, HEAD, and OPTIONS. Mark a write the server dedupes + `idempotent: true` to replay it too. A server that rejects rate-limited + requests before it runs them can pass `retryableStatuses` with 429 mapped to + `"any"`. +- `serverDelayMs` reads a provider's own rate-limit header; `serverDelayUntil` + turns a reset time into a delay, corrected by the response `Date`. + +`nextRetryDelayMs` is the decision on its own, for hosts with their own loop. + +## License + +[FSL-1.1-Apache-2.0](LICENSE.md) diff --git a/packages/http/package.json b/packages/http/package.json new file mode 100644 index 0000000000..ee159ea7b1 --- /dev/null +++ b/packages/http/package.json @@ -0,0 +1,90 @@ +{ + "name": "@sentry/http", + "version": "0.1.0-dev.0", + "description": "HTTP response caching, body compression, and retries over the Fetch API, with pluggable cache stores", + "type": "module", + "license": "FSL-1.1-Apache-2.0", + "author": "Sentry", + "homepage": "https://github.com/getsentry/toolkit/tree/main/packages/http#readme", + "keywords": [ + "sentry", + "http", + "cache", + "http-cache", + "retry", + "fetch" + ], + "bugs": { + "url": "https://github.com/getsentry/toolkit/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/getsentry/toolkit.git", + "directory": "packages/http" + }, + "engines": { + "node": ">=22" + }, + "sideEffects": false, + "sentryCi": { + "e2e": "test:package" + }, + "files": [ + "dist", + "LICENSE.md", + "README.md" + ], + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./codec": { + "types": "./src/codec.ts", + "default": "./src/codec.ts" + } + }, + "publishConfig": { + "access": "public", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + }, + "./codec": { + "import": { + "types": "./dist/codec.d.ts", + "default": "./dist/codec.js" + }, + "require": { + "types": "./dist/codec.d.cts", + "default": "./dist/codec.cjs" + } + } + } + }, + "scripts": { + "build": "tsdown", + "test": "vitest run", + "test:ci": "vitest run --reporter=default --reporter=junit --outputFile=tests.junit.xml", + "test:package": "sh test/package/check.sh", + "typecheck": "tsc --noEmit && tsc -p tsconfig.browser.json" + }, + "dependencies": { + "http-cache-semantics": "^4.2.0" + }, + "devDependencies": { + "@types/http-cache-semantics": "^4.2.0", + "@types/node": "catalog:", + "fast-check": "^4.8.0", + "tsdown": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/packages/http/src/body.ts b/packages/http/src/body.ts new file mode 100644 index 0000000000..5d6aee69f7 --- /dev/null +++ b/packages/http/src/body.ts @@ -0,0 +1,55 @@ +/** + * The shape of a stored response body and of the codec that produces it. + * The compressing codec in `@sentry/http/codec` needs `node:zlib`, so it is + * a separate entry point and the cache policy and stores stay portable. + */ + +/** How an entry's body bytes are encoded. */ +export type BodyEncoding = "zstd" | "br" | "identity"; + +/** A body as stored: its bytes plus what is needed to decode them. */ +export type EncodedBody = { + bytes: Uint8Array; + encoding: BodyEncoding; + /** + * Compression dictionary the bytes need. Never set today; recorded so a + * later dictionary rollout can tell its entries apart from plain ones. + */ + dictId?: string; + /** Size of the original body, which bounds decompression. */ + rawSize: number; +}; + +/** Encodes and decodes cached bodies. */ +export type BodyCodec = { + /** Compress a body for storage. */ + encode(raw: Uint8Array): Promise; + /** + * Restore a stored body. Returns `undefined` when this runtime cannot read + * the entry (zstd on Node < 22.15, or a dictionary it does not have), so the + * caller treats it as a miss. Throws when the bytes are corrupt or do not + * decode to `rawSize` bytes. + */ + decode(body: EncodedBody): Promise; +}; + +/** + * A codec that stores bodies as they are, for runtimes without `node:zlib` + * and for tests. It still skips entries that another codec compressed. + */ +export const identityCodec: BodyCodec = { + async encode(raw) { + return { bytes: raw, encoding: "identity", rawSize: raw.byteLength }; + }, + async decode(body) { + if (body.dictId !== undefined || body.encoding !== "identity") { + return; + } + if (body.bytes.byteLength !== body.rawSize) { + throw new Error( + `Cached body has ${body.bytes.byteLength} bytes, expected ${body.rawSize}`, + ); + } + return body.bytes; + }, +}; diff --git a/packages/toolkit-core/src/response-cache/codec.test.ts b/packages/http/src/codec.test.ts similarity index 100% rename from packages/toolkit-core/src/response-cache/codec.test.ts rename to packages/http/src/codec.test.ts diff --git a/packages/toolkit-core/src/response-cache/codec.ts b/packages/http/src/codec.ts similarity index 96% rename from packages/toolkit-core/src/response-cache/codec.ts rename to packages/http/src/codec.ts index 6c65d9293f..e68a7c2842 100644 --- a/packages/toolkit-core/src/response-cache/codec.ts +++ b/packages/http/src/codec.ts @@ -11,9 +11,9 @@ // A namespace import, so a missing `zstdCompress` (Node < 22.15) is // `undefined` rather than a link error. import * as nodeZlib from "node:zlib"; -import type { BodyCodec, EncodedBody } from "@sentry/api/client"; +import type { BodyCodec, EncodedBody } from "./body.js"; -export type { BodyCodec, BodyEncoding, EncodedBody } from "@sentry/api/client"; +export type { BodyCodec, BodyEncoding, EncodedBody } from "./body.js"; /** Bodies smaller than this are stored uncompressed. */ export const MIN_COMPRESSED_BYTES = 256; diff --git a/packages/http/src/fetch.test.ts b/packages/http/src/fetch.test.ts new file mode 100644 index 0000000000..b1ab04e10c --- /dev/null +++ b/packages/http/src/fetch.test.ts @@ -0,0 +1,207 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { identityCodec as codec } from "./body.js"; +import { type CachedFetchOptions, fetchWithCache } from "./fetch.js"; +import { buildCacheKey } from "./keys.js"; +import { createMemoryStore, type MemoryStore } from "./memory-store.js"; +import type { CacheStore } from "./store.js"; + +const URL = "https://api.example.com/repos/acme/web/pulls/1"; +const IDENTITY = "installation:1"; +const MINUTE = 60_000; + +function json( + body: unknown, + headers: Record = {}, + status = 200, +): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json", ...headers }, + }); +} + +/** A `send` that answers with `responses` in order and records its headers. */ +function server(...responses: (Response | Error)[]) { + const calls: Record[] = []; + const send = vi.fn(async (headers: Record) => { + calls.push(headers); + const next = responses.shift(); + if (!next) { + throw new Error("unexpected request"); + } + if (next instanceof Error) { + throw next; + } + return next; + }); + return { send, calls }; +} + +function read( + store: CacheStore, + send: CachedFetchOptions["send"], + options: Partial = {}, +): Promise { + return fetchWithCache({ + store, + codec, + identity: IDENTITY, + url: URL, + ttlMs: MINUTE, + send, + ...options, + }); +} + +let store: MemoryStore; + +beforeEach(() => { + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); + store = createMemoryStore(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("fetchWithCache", () => { + it("stores a response and serves it with no request while fresh", async () => { + const { send } = server(json({ v: 1 })); + + expect(await (await read(store, send)).json()).toEqual({ v: 1 }); + expect(await (await read(store, send)).json()).toEqual({ v: 1 }); + expect(send).toHaveBeenCalledTimes(1); + }); + + it("revalidates a stale entry and serves its body on a 304", async () => { + const { send, calls } = server( + json({ v: 1 }, { etag: '"v1"' }), + new Response(null, { status: 304, headers: { etag: '"v1"' } }), + ); + await read(store, send, { ttlMs: 0 }); + + const response = await read(store, send, { ttlMs: 0 }); + + expect(await response.json()).toEqual({ v: 1 }); + expect(calls).toEqual([{}, { "if-none-match": '"v1"' }]); + }); + + it("asks again without validators after a 304 that does not match", async () => { + const { send, calls } = server( + json({ v: 1 }, { etag: '"v1"' }), + new Response(null, { status: 304, headers: { etag: '"other"' } }), + json({ v: 2 }, { etag: '"v2"' }), + ); + await read(store, send, { ttlMs: 0 }); + + const response = await read(store, send, { ttlMs: 0 }); + + expect(await response.json()).toEqual({ v: 2 }); + expect(calls).toEqual([{}, { "if-none-match": '"v1"' }, {}]); + }); + + it.each([ + ["a thrown error", new TypeError("fetch failed")], + ["a 503", json({ detail: "down" }, {}, 503)], + ["a 429", json({ detail: "slow down" }, {}, 429)], + ])("serves the stale entry on %s with staleIfError", async (_, failure) => { + const createdAt = Date.now(); + const { send } = server(json({ v: 1 }), failure); + const onStale = vi.fn(); + await read(store, send, { staleIfError: true }); + vi.setSystemTime(Date.now() + 2 * MINUTE); + + const response = await read(store, send, { + staleIfError: true, + onStale, + }); + + expect(await response.json()).toEqual({ v: 1 }); + expect(onStale).toHaveBeenCalledWith(createdAt); + }); + + it("passes a failure through without staleIfError", async () => { + const { send } = server( + json({ v: 1 }, { etag: '"v1"' }), + json({ detail: "down" }, {}, 503), + new TypeError("fetch failed"), + ); + await read(store, send, { ttlMs: 0 }); + + expect((await read(store, send, { ttlMs: 0 })).status).toBe(503); + await expect(read(store, send, { ttlMs: 0 })).rejects.toThrow( + "fetch failed", + ); + }); + + it("drops the entry on a client error, so a later failure cannot serve it", async () => { + const { send } = server( + json({ v: 1 }), + json({ message: "Not Found" }, {}, 404), + json({ detail: "down" }, {}, 503), + ); + const options = { staleIfError: true, ttlMs: 0 }; + await read(store, send, options); + + expect((await read(store, send, options)).status).toBe(404); + expect((await read(store, send, options)).status).toBe(503); + expect(store.stats().entries).toBe(0); + }); + + it("does not store a stale entry it served", async () => { + const { send } = server(json({ v: 1 }), new TypeError("fetch failed")); + await read(store, send, { staleIfError: true, ttlMs: 0 }); + const createdAt = ( + await store.get(await buildCacheKey("GET", URL, IDENTITY)) + )?.createdAt; + vi.setSystemTime(Date.now() + MINUTE); + + await read(store, send, { staleIfError: true, ttlMs: 0 }); + + const entry = await store.get(await buildCacheKey("GET", URL, IDENTITY)); + expect(entry?.createdAt).toBe(createdAt); + }); + + it("treats an unreadable entry as a miss and drops it", async () => { + const key = await buildCacheKey("GET", URL, IDENTITY); + const { send } = server(json({ v: 1 }), json({ v: 2 })); + await read(store, send); + const entry = await store.get(key); + if (!entry) { + throw new Error("expected an entry"); + } + await store.set(key, { ...entry, policy: { v: 999 } }, MINUTE); + const onCacheError = vi.fn(); + + const response = await read(store, send, { onCacheError }); + + expect(await response.json()).toEqual({ v: 2 }); + expect(onCacheError).toHaveBeenCalledOnce(); + }); + + it("never fails a request when the store fails", async () => { + const failure = new Error("store down"); + const broken: CacheStore = { + get: () => Promise.reject(failure), + set: () => Promise.reject(failure), + delete: () => Promise.reject(failure), + deleteMatching: () => Promise.reject(failure), + }; + const onCacheError = vi.fn(); + const { send } = server(json({ v: 1 })); + + const response = await read(broken, send, { onCacheError }); + + expect(await response.json()).toEqual({ v: 1 }); + expect(onCacheError).toHaveBeenCalledWith(failure); + }); + + it("keeps identities apart", async () => { + const { send } = server(json({ v: "a" }), json({ v: "b" })); + await read(store, send, { identity: "a" }); + + const response = await read(store, send, { identity: "b" }); + + expect(await response.json()).toEqual({ v: "b" }); + }); +}); diff --git a/packages/http/src/fetch.ts b/packages/http/src/fetch.ts new file mode 100644 index 0000000000..05083a6fc1 --- /dev/null +++ b/packages/http/src/fetch.ts @@ -0,0 +1,179 @@ +/** + * One GET through the cache: serve a fresh entry, revalidate a stale one + * with its validators, serve the stale entry when the server fails (with + * `staleIfError`), and store what the server sends back. A failure of the + * cache itself is a miss, so it never fails the request. + */ + +import type { BodyCodec } from "./body.js"; +import { buildCacheKey } from "./keys.js"; +import { + type CacheLookup, + type FreshnessOptions, + lookupResponse, + storeResponse, +} from "./policy.js"; +import type { CacheStore } from "./store.js"; + +export type CachedFetchOptions = FreshnessOptions & { + store: CacheStore; + codec: BodyCodec; + /** + * Who the response belongs to: a stable hash of the credential or login + * that `send` uses, never a raw token. An entry of one identity never + * serves another. + */ + identity: string; + url: string; + /** + * Defaults to `buildCacheKey("GET", url, identity)`. Pass one to add + * request parts that change the response, such as `Accept`. + */ + key?: string; + /** Headers `send` sends, for `Vary` matching. */ + requestHeaders?: Record; + /** Send the GET with these headers added, such as `If-None-Match`. */ + send: (headers: Record) => Promise; + /** + * Called with the entry's `createdAt` when a stale entry is served + * because `send` threw or the server answered 429 or 5xx. + */ + onStale?: (createdAt: number) => void; + /** Called when reading or writing the cache fails; the request stands. */ + onCacheError?: (error: unknown) => void; + /** Store only JSON bodies. */ + requireJson?: boolean; +}; + +/** + * A rate limit or server error says nothing about access, so it keeps the + * entry, and may serve it with `staleIfError`. + */ +function isServerFailure(status: number): boolean { + return status === 429 || status >= 500; +} + +function freshness(options: FreshnessOptions): FreshnessOptions { + const { ttlMs, maxTtlMs, retainMs, staleIfError } = options; + return { + ttlMs, + ...(maxTtlMs === undefined ? {} : { maxTtlMs }), + ...(retainMs === undefined ? {} : { retainMs }), + ...(staleIfError === undefined ? {} : { staleIfError }), + }; +} + +/** + * Send one GET through the cache. + * + * A 403, 404, or other client error drops the entry, so a later error + * cannot serve it to a credential that lost access. + * + * @throws What `send` throws, when no stale entry can be served instead + */ +export async function fetchWithCache( + options: CachedFetchOptions, +): Promise { + const { store, codec, identity, url, requestHeaders = {}, send } = options; + const report = (error: unknown): void => options.onCacheError?.(error); + const key = options.key ?? (await buildCacheKey("GET", url, identity)); + + let lookup: CacheLookup | undefined; + try { + lookup = await lookupResponse({ + ...freshness(options), + store, + codec, + key, + url, + requestHeaders, + onRenewError: report, + }); + } catch (error) { + // A corrupt or unreadable entry is a miss; drop it. + report(error); + await store.delete(key).catch(report); + } + if (lookup?.kind === "hit") { + return lookup.response; + } + const stale = lookup; + + async function serveStale(): Promise { + if (!stale?.serveStale) { + return; + } + try { + const response = await stale.serveStale(); + if (response) { + options.onStale?.(stale.createdAt); + } + return response; + } catch (error) { + report(error); + return; + } + } + + /** The stale entry in place of a failed `send`, or the failure. */ + async function serveStaleOrThrow(error: unknown): Promise { + const fallback = await serveStale(); + if (fallback) { + return fallback; + } + throw error; + } + + let response: Response; + try { + response = await send(stale?.conditionalHeaders ?? {}); + } catch (error) { + return await serveStaleOrThrow(error); + } + if (stale && response.status === 304) { + const revalidated = await stale.revalidate(response).catch(report); + if (revalidated) { + return revalidated; + } + // A 304 that does not match the entry: ask again without validators. + try { + response = await send({}); + } catch (error) { + return await serveStaleOrThrow(error); + } + } + + if (isServerFailure(response.status)) { + const fallback = await serveStale(); + if (!fallback) { + return response; + } + // Some bodies finish cancelling only when their source does, so this + // does not wait. + response.body?.cancel().catch(() => undefined); + return fallback; + } + if (!response.ok) { + if (lookup) { + await store.delete(key).catch(report); + } + return response; + } + + try { + await storeResponse({ + ...freshness(options), + store, + codec, + key, + identity, + url, + requestHeaders, + response: response.clone(), + ...(options.requireJson ? { requireJson: true } : {}), + }); + } catch (error) { + report(error); + } + return response; +} diff --git a/packages/http/src/index.ts b/packages/http/src/index.ts new file mode 100644 index 0000000000..30166f1f05 --- /dev/null +++ b/packages/http/src/index.ts @@ -0,0 +1,45 @@ +/** + * HTTP response caching and retries over the Fetch API: freshness and + * revalidation through `http-cache-semantics`, stale-if-error, identity-scoped + * keys, a pluggable `CacheStore` with a byte-budgeted memory store, and + * idempotency-aware retries with backoff and `Retry-After`. No Node APIs; the + * compressing body codec is in `@sentry/http/codec`. + */ + +export { + type BodyCodec, + type BodyEncoding, + type EncodedBody, + identityCodec, +} from "./body.js"; +export { type CachedFetchOptions, fetchWithCache } from "./fetch.js"; +export { buildCacheKey, normalizeUrl } from "./keys.js"; +export { + createMemoryStore, + type MemoryStore, + type MemoryStoreOptions, +} from "./memory-store.js"; +export { + type CacheLookup, + type FreshnessOptions, + type LookupOptions, + lookupResponse, + REVALIDATION_WINDOW_MS, + type StoreOptions, + storeResponse, +} from "./policy.js"; +export { + DEFAULT_RETRYABLE_STATUSES, + fetchWithRetry, + isIdempotentRequest, + nextRetryDelayMs, + parseRetryAfterMs, + type RetryableStatuses, + type RetryAttempt, + type RetryOptions, + type RetryPolicy, + type RetryReplay, + serverDelayUntil, + sleep, +} from "./retry.js"; +export type { CacheEntry, CacheStore } from "./store.js"; diff --git a/packages/http/src/keys.property.test.ts b/packages/http/src/keys.property.test.ts new file mode 100644 index 0000000000..aecf6ffa2f --- /dev/null +++ b/packages/http/src/keys.property.test.ts @@ -0,0 +1,164 @@ +/** + * Property-based tests for cache key generation and URL normalization. + */ + +import { + array, + asyncProperty, + constantFrom, + assert as fcAssert, + property, + string, + tuple, +} from "fast-check"; +import { describe, expect, test } from "vitest"; +import { buildCacheKey, normalizeUrl } from "./keys.js"; + +const DEFAULT_NUM_RUNS = 50; + +/** Any non-empty identity; scoping across identities is in keys.test.ts. */ +const IDENTITY = "test-identity"; + +// --------------------------------------------------------------------------- +// Arbitraries +// --------------------------------------------------------------------------- + +/** Generate valid HTTP methods */ +const methodArb = constantFrom("GET", "POST", "PUT", "DELETE", "PATCH"); + +/** Generate simple path segments */ +const pathSegmentArb = string({ minLength: 1, maxLength: 20 }).filter((s) => + /^[a-zA-Z0-9_-]+$/.test(s), +); + +/** Generate URL-like strings with paths and query params */ +const sentryUrlArb = tuple( + constantFrom( + "https://us.sentry.io", + "https://de.sentry.io", + "https://sentry.io", + ), + array(pathSegmentArb, { minLength: 1, maxLength: 5 }), + array( + tuple( + string({ minLength: 1, maxLength: 10 }).filter((s) => + /^[a-zA-Z]+$/.test(s), + ), + string({ minLength: 1, maxLength: 20 }).filter((s) => + /^[a-zA-Z0-9]+$/.test(s), + ), + ), + { minLength: 0, maxLength: 4 }, + ), +).map(([base, paths, params]) => { + const pathStr = `/api/0/${paths.join("/")}`; + const query = + params.length > 0 + ? `?${params.map(([k, v]) => `${k}=${v}`).join("&")}` + : ""; + return `${base}${pathStr}${query}`; +}); + +// --------------------------------------------------------------------------- +// Tests: buildCacheKey +// --------------------------------------------------------------------------- + +describe("property: buildCacheKey", () => { + test("produces a 64-char hex string (SHA-256)", async () => { + await fcAssert( + asyncProperty(methodArb, sentryUrlArb, async (method, url) => { + expect(await buildCacheKey(method, url, IDENTITY)).toMatch( + /^[0-9a-f]{64}$/, + ); + }), + { numRuns: DEFAULT_NUM_RUNS }, + ); + }); + + test("is deterministic — same inputs produce same key", async () => { + await fcAssert( + asyncProperty(methodArb, sentryUrlArb, async (method, url) => { + expect(await buildCacheKey(method, url, IDENTITY)).toBe( + await buildCacheKey(method, url, IDENTITY), + ); + }), + { numRuns: DEFAULT_NUM_RUNS }, + ); + }); + + test("different methods produce different keys for same URL", async () => { + await fcAssert( + asyncProperty(sentryUrlArb, async (url) => { + expect(await buildCacheKey("GET", url, IDENTITY)).not.toBe( + await buildCacheKey("POST", url, IDENTITY), + ); + }), + { numRuns: DEFAULT_NUM_RUNS }, + ); + }); + + test("query param order does not affect the key", async () => { + await fcAssert( + asyncProperty( + constantFrom("https://us.sentry.io", "https://de.sentry.io"), + pathSegmentArb, + async (base, path) => { + const url1 = `${base}/api/0/${path}?a=1&b=2&c=3`; + const url2 = `${base}/api/0/${path}?c=3&a=1&b=2`; + expect(await buildCacheKey("GET", url1, IDENTITY)).toBe( + await buildCacheKey("GET", url2, IDENTITY), + ); + }, + ), + { numRuns: DEFAULT_NUM_RUNS }, + ); + }); + + test("method comparison is case-insensitive", async () => { + await fcAssert( + asyncProperty(sentryUrlArb, async (url) => { + expect(await buildCacheKey("get", url, IDENTITY)).toBe( + await buildCacheKey("GET", url, IDENTITY), + ); + }), + { numRuns: DEFAULT_NUM_RUNS }, + ); + }); +}); + +// --------------------------------------------------------------------------- +// Tests: normalizeUrl +// --------------------------------------------------------------------------- + +describe("property: normalizeUrl", () => { + test("sorts query parameters alphabetically", () => { + const normalized = normalizeUrl("GET", "https://sentry.io/api?z=1&a=2&m=3"); + expect(normalized).toBe("GET|https://sentry.io/api?a=2&m=3&z=1"); + }); + + test("uppercases the method", () => { + fcAssert( + property( + constantFrom("get", "post", "put", "delete"), + sentryUrlArb, + (method, url) => { + const normalized = normalizeUrl(method, url); + expect(normalized.startsWith(method.toUpperCase())).toBe(true); + }, + ), + { numRuns: DEFAULT_NUM_RUNS }, + ); + }); + + test("produces pipe-separated method|url format", () => { + fcAssert( + property(methodArb, sentryUrlArb, (method, url) => { + const normalized = normalizeUrl(method, url); + expect(normalized).toContain("|"); + const [m] = normalized.split("|", 1); + expect(m).toBe(method.toUpperCase()); + }), + { numRuns: DEFAULT_NUM_RUNS }, + ); + }); +}); diff --git a/packages/http/src/keys.test.ts b/packages/http/src/keys.test.ts new file mode 100644 index 0000000000..c52d0f6a96 --- /dev/null +++ b/packages/http/src/keys.test.ts @@ -0,0 +1,64 @@ +import { createHmac } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { buildCacheKey, normalizeUrl } from "./keys.js"; + +const URL_A = "https://us.sentry.io/api/0/organizations/acme/projects/?b=2&a=1"; + +describe("normalizeUrl", () => { + it("uppercases the method and sorts query params, keeping the host", () => { + expect(normalizeUrl("get", URL_A)).toBe( + "GET|https://us.sentry.io/api/0/organizations/acme/projects/?a=1&b=2", + ); + }); + + it("keeps the order of repeated query params", () => { + expect( + normalizeUrl( + "GET", + "https://us.sentry.io/api/0/issues/1/events/latest/?collapse=fullRelease&a=1&collapse=adjacentEvents", + ), + ).toBe( + "GET|https://us.sentry.io/api/0/issues/1/events/latest/?a=1&collapse=fullRelease&collapse=adjacentEvents", + ); + }); + + it("keeps self-hosted hosts", () => { + expect( + normalizeUrl("GET", "https://sentry.mycompany.internal/api/0/issues/"), + ).toBe("GET|https://sentry.mycompany.internal/api/0/issues/"); + }); + + it("throws on a URL it cannot parse", () => { + expect(() => normalizeUrl("GET", "not a url")).toThrow(TypeError); + }); +}); + +describe("buildCacheKey", () => { + it("gives two identities different keys for the same URL", async () => { + expect(await buildCacheKey("GET", URL_A, "alice")).not.toBe( + await buildCacheKey("GET", URL_A, "bob"), + ); + }); + + it("gives the same path on two Sentry hosts different keys", async () => { + const path = "/api/0/organizations/acme/projects/"; + expect( + await buildCacheKey("GET", `https://us.sentry.io${path}`, "alice"), + ).not.toBe( + await buildCacheKey("GET", `https://sentry.example.com${path}`, "alice"), + ); + }); + + it("matches node:crypto HMAC-SHA256, so existing CLI cache entries still hit", async () => { + const identity = "oauth:3f2a9c"; + const expected = createHmac("sha256", identity) + .update(normalizeUrl("GET", URL_A)) + .digest("hex"); + + expect(await buildCacheKey("GET", URL_A, identity)).toBe(expected); + }); + + it("refuses an empty identity, which would not scope entries", async () => { + await expect(buildCacheKey("GET", URL_A, "")).rejects.toThrow(TypeError); + }); +}); diff --git a/packages/http/src/keys.ts b/packages/http/src/keys.ts new file mode 100644 index 0000000000..978e44a15d --- /dev/null +++ b/packages/http/src/keys.ts @@ -0,0 +1,68 @@ +/** + * Identity-scoped cache keys. Uses WebCrypto, so it runs in Node, Cloudflare + * Workers, and browsers. + */ + +const encoder = new TextEncoder(); + +/** + * Normalize method + URL into a stable string for cache key derivation. + * Keeps the host, so the same path on two servers gets two keys, and + * sorts query params by name so `?a=1&b=2` and `?b=2&a=1` match. + * + * @throws {TypeError} If the URL cannot be parsed + */ +export function normalizeUrl(method: string, url: string): string { + const parsed = new URL(url); + const sortedParams = new URLSearchParams( + [...parsed.searchParams.entries()].sort(([a], [b]) => { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; + }), + ); + parsed.search = sortedParams.toString() ? `?${sortedParams.toString()}` : ""; + return `${method.toUpperCase()}|${parsed.toString()}`; +} + +/** + * Build a cache key from the requesting identity, method, and URL: the + * hex HMAC-SHA256 of {@link normalizeUrl} keyed by `identity`. + * + * `identity` scopes entries so one user never receives another's response. + * It must be a stable hash of who is asking, never a raw token, and should + * not change when an access token is refreshed for the same login. Keys + * match `node:crypto`'s `createHmac("sha256", identity)`, so entries written + * by `@sentry/api` and earlier CLI versions are still found. + * + * @throws {TypeError} If `identity` is empty or the URL cannot be parsed + */ +export async function buildCacheKey( + method: string, + url: string, + identity: string, +): Promise { + if (!identity) { + throw new TypeError("A cache key needs a non-empty identity"); + } + const normalized = normalizeUrl(method, url); + const key = await crypto.subtle.importKey( + "raw", + encoder.encode(identity), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const signature = await crypto.subtle.sign( + "HMAC", + key, + encoder.encode(normalized), + ); + return Array.from(new Uint8Array(signature), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); +} diff --git a/packages/http/src/memory-store.test.ts b/packages/http/src/memory-store.test.ts new file mode 100644 index 0000000000..802f4de5b4 --- /dev/null +++ b/packages/http/src/memory-store.test.ts @@ -0,0 +1,250 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { type EncodedBody, identityCodec } from "./body.js"; +import { buildCacheKey } from "./keys.js"; +import { createMemoryStore, ENTRY_OVERHEAD_BYTES } from "./memory-store.js"; +import type { CacheEntry } from "./store.js"; + +const API = "https://us.sentry.io/api/0"; +const MINUTE = 60_000; +const encoder = new TextEncoder(); +const codec = identityCodec; + +/** A stored body of exactly `size` bytes. */ +function bodyOfSize(size: number, rawSize = size): EncodedBody { + return { bytes: new Uint8Array(size), encoding: "identity", rawSize }; +} + +function entry( + url: string, + body: EncodedBody, + identity = "identity-a", +): CacheEntry { + return { + url, + identity, + status: 200, + headers: {}, + body, + policy: {}, + createdAt: Date.now(), + }; +} + +/** A trace-like JSON body: many similar spans, as real traces have. */ +function traceBody(targetBytes: number): Uint8Array { + const spans: string[] = []; + let size = 0; + for (let i = 0; size < targetBytes; i++) { + const span = JSON.stringify({ + span_id: i.toString(16).padStart(16, "0"), + parent_span_id: (i >> 1).toString(16).padStart(16, "0"), + op: i % 3 === 0 ? "db.query" : "http.client", + description: `SELECT * FROM sentry_groupedmessage WHERE id = ${i}`, + start_timestamp: 1_700_000_000 + i / 1000, + duration: (i % 97) + 0.25, + }); + spans.push(span); + size += span.length + 1; + } + return encoder.encode(`[${spans.join(",")}]`); +} + +describe("createMemoryStore", () => { + beforeEach(() => { + vi.setSystemTime(Date.now()); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("returns a stored entry whose body decodes to the original", async () => { + const store = createMemoryStore(); + const url = `${API}/organizations/acme/issues/?query=is%3Aunresolved`; + const raw = traceBody(4096); + const key = await buildCacheKey("GET", url, "identity-a"); + + await store.set(key, entry(url, await codec.encode(raw)), MINUTE); + const cached = await store.get(key); + + expect(cached?.url).toBe(url); + expect(cached && (await codec.decode(cached.body))).toEqual(raw); + expect(await store.get("some-other-key")).toBeUndefined(); + }); + + it("drops an entry once its TTL has passed", async () => { + const store = createMemoryStore(); + await store.set("k", entry(`${API}/issues/1/`, bodyOfSize(10)), MINUTE); + + vi.setSystemTime(Date.now() + MINUTE - 1); + expect(await store.get("k")).toBeDefined(); + + vi.setSystemTime(Date.now() + 1); + expect(await store.get("k")).toBeUndefined(); + expect(store.stats()).toEqual({ entries: 0, bytes: 0 }); + }); + + it("does not store an entry without a positive TTL", async () => { + const store = createMemoryStore(); + await store.set("zero", entry(`${API}/a/`, bodyOfSize(10)), 0); + await store.set("nan", entry(`${API}/b/`, bodyOfSize(10)), Number.NaN); + + expect(store.stats().entries).toBe(0); + }); + + it("evicts the least recently used entry when over budget", async () => { + const size = 100 + ENTRY_OVERHEAD_BYTES; + const store = createMemoryStore({ maxBytes: size * 3 }); + for (const key of ["a", "b", "c"]) { + await store.set(key, entry(`${API}/${key}/`, bodyOfSize(100)), MINUTE); + } + + // Reading `a` makes `b` the least recently used. + await store.get("a"); + await store.set("d", entry(`${API}/d/`, bodyOfSize(100)), MINUTE); + + expect(await store.get("b")).toBeUndefined(); + for (const key of ["a", "c", "d"]) { + expect(await store.get(key)).toBeDefined(); + } + expect(store.stats()).toEqual({ entries: 3, bytes: size * 3 }); + }); + + it("evicts as many entries as a large one needs", async () => { + const store = createMemoryStore({ maxBytes: 4 * ENTRY_OVERHEAD_BYTES }); + for (const key of ["a", "b", "c", "d"]) { + await store.set(key, entry(`${API}/${key}/`, bodyOfSize(0)), MINUTE); + } + + await store.set( + "big", + entry(`${API}/big/`, bodyOfSize(2 * ENTRY_OVERHEAD_BYTES)), + MINUTE, + ); + + expect(await store.get("a")).toBeUndefined(); + expect(await store.get("b")).toBeUndefined(); + expect(await store.get("c")).toBeUndefined(); + expect(await store.get("d")).toBeDefined(); + expect(await store.get("big")).toBeDefined(); + }); + + it("does not store a body over the per-entry cap", async () => { + const store = createMemoryStore({ maxEntryBytes: 1000 }); + await store.set("k", entry(`${API}/a/`, bodyOfSize(1000)), MINUTE); + expect(await store.get("k")).toBeDefined(); + + // An oversized replacement removes the older response too. + await store.set("k", entry(`${API}/a/`, bodyOfSize(1001)), MINUTE); + + expect(await store.get("k")).toBeUndefined(); + expect(store.stats()).toEqual({ entries: 0, bytes: 0 }); + }); + + it("does not store a body whose original size is over the ceiling", async () => { + const store = createMemoryStore({ maxRawBytes: 10_000 }); + await store.set("k", entry(`${API}/a/`, bodyOfSize(100, 10_001)), MINUTE); + + expect(await store.get("k")).toBeUndefined(); + }); + + it("does not store an entry larger than the whole budget", async () => { + const store = createMemoryStore({ maxBytes: 2048, maxEntryBytes: 4096 }); + await store.set("small", entry(`${API}/a/`, bodyOfSize(10)), MINUTE); + await store.set("huge", entry(`${API}/b/`, bodyOfSize(3000)), MINUTE); + + expect(await store.get("huge")).toBeUndefined(); + expect(await store.get("small")).toBeDefined(); + }); + + it("stays within its budget when many identities fill it", async () => { + const maxBytes = 256 * 1024; + const store = createMemoryStore({ maxBytes }); + let peak = 0; + let last = ""; + for (let user = 0; user < 500; user++) { + const identity = `user-${user}`; + for (let page = 0; page < 10; page++) { + const url = `${API}/organizations/acme/issues/?cursor=${page}`; + last = await buildCacheKey("GET", url, identity); + // Bodies from raw sub-256-byte responses up to 8 KB. + const body = bodyOfSize(((user * 31 + page * 7) % 64) * 128); + await store.set(last, entry(url, body, identity), MINUTE); + peak = Math.max(peak, store.stats().bytes); + } + } + + expect(peak).toBeLessThanOrEqual(maxBytes); + expect(store.stats().entries).toBeGreaterThan(0); + expect(await store.get(last)).toBeDefined(); + }); + + it("deletes only the given identity's entries under a prefix", async () => { + const store = createMemoryStore(); + const issues = `${API}/organizations/acme/issues/`; + const projects = `${API}/organizations/acme/projects/`; + await store.set("a-issues", entry(issues, bodyOfSize(10), "a"), MINUTE); + await store.set("a-projects", entry(projects, bodyOfSize(10), "a"), MINUTE); + await store.set("b-issues", entry(issues, bodyOfSize(10), "b"), MINUTE); + + await store.deleteMatching("a", issues); + + expect(await store.get("a-issues")).toBeUndefined(); + expect(await store.get("a-projects")).toBeDefined(); + expect(await store.get("b-issues")).toBeDefined(); + expect(store.stats().entries).toBe(2); + }); + + it("deletes one entry and frees its bytes", async () => { + const store = createMemoryStore(); + await store.set("a", entry(`${API}/a/`, bodyOfSize(10)), MINUTE); + await store.set("b", entry(`${API}/b/`, bodyOfSize(10)), MINUTE); + + await store.delete("a"); + await store.delete("missing"); + + expect(await store.get("a")).toBeUndefined(); + expect(await store.get("b")).toBeDefined(); + expect(store.stats()).toEqual({ + entries: 1, + bytes: 10 + ENTRY_OVERHEAD_BYTES, + }); + }); + + it("counts a replaced entry only once", async () => { + const store = createMemoryStore(); + await store.set("k", entry(`${API}/a/`, bodyOfSize(500)), MINUTE); + await store.set("k", entry(`${API}/a/`, bodyOfSize(200)), MINUTE); + + expect(store.stats()).toEqual({ + entries: 1, + bytes: 200 + ENTRY_OVERHEAD_BYTES, + }); + }); + + it.each([ + ["Uint8Array", new Uint8Array(1024 * 1024)], + // `Buffer#slice` shares memory, unlike `Uint8Array#slice`. + ["Buffer", Buffer.alloc(1024 * 1024)], + ])("does not keep the larger buffer behind a %s view", async (_, backing) => { + const store = createMemoryStore(); + const bytes = backing.subarray(100, 400); + await store.set( + "k", + entry(`${API}/a/`, { bytes, encoding: "identity", rawSize: 300 }), + MINUTE, + ); + + const cached = await store.get("k"); + + expect(cached?.body.bytes.buffer.byteLength).toBe(300); + }); + + it.each([ + { maxBytes: 0 }, + { maxEntryBytes: -1 }, + { maxRawBytes: Number.POSITIVE_INFINITY }, + ])("rejects a non-positive or infinite limit: %o", (options) => { + expect(() => createMemoryStore(options)).toThrow(RangeError); + }); +}); diff --git a/packages/http/src/memory-store.ts b/packages/http/src/memory-store.ts new file mode 100644 index 0000000000..ee461a95a4 --- /dev/null +++ b/packages/http/src/memory-store.ts @@ -0,0 +1,145 @@ +/** + * In-memory {@link CacheStore} with a byte budget, for one process and for + * tests. Evicts least recently used entries first. Holds no timers: expired + * entries are dropped when read, or evicted like any other entry. + */ + +import type { CacheEntry, CacheStore } from "./store.js"; + +const MIB = 1024 * 1024; + +/** + * Bytes charged per entry on top of its body, for the key, URL, headers, + * serialized policy, and bookkeeping. An estimate, so that many small + * entries (bodies under 256 bytes are stored raw) cannot outgrow the budget. + */ +export const ENTRY_OVERHEAD_BYTES = 1024; + +export type MemoryStoreOptions = { + /** Budget over all entries, in bytes. Defaults to 24 MiB. */ + maxBytes?: number; + /** Largest stored (compressed) body, in bytes. Defaults to 1 MiB. */ + maxEntryBytes?: number; + /** + * Largest original body, in bytes, which bounds memory while decoding. + * Defaults to 32 MiB. + */ + maxRawBytes?: number; +}; + +export type MemoryStore = CacheStore & { + /** Current entry count and bytes charged against the budget. */ + stats(): { entries: number; bytes: number }; +}; + +type Slot = { entry: CacheEntry; size: number; expiresAt: number }; + +function limit(name: string, value: number | undefined, fallback: number) { + if (value === undefined) { + return fallback; + } + if (!(Number.isFinite(value) && value > 0)) { + throw new RangeError(`${name} must be a positive number, got ${value}`); + } + return value; +} + +/** + * Copy `bytes` when it is a view into a larger buffer, so the store never + * keeps memory it does not count. Copies with the `Uint8Array` constructor, + * because `Buffer#slice` returns a view that shares the original memory. + */ +function ownBytes(bytes: Uint8Array): Uint8Array { + return bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength + ? bytes + : new Uint8Array(bytes); +} + +/** + * Create an empty memory store. Entries are kept by reference; callers must + * not mutate an entry after storing it or one returned by `get`. + * + * @throws {RangeError} If a limit is not a positive number + */ +export function createMemoryStore( + options: MemoryStoreOptions = {}, +): MemoryStore { + const maxBytes = limit("maxBytes", options.maxBytes, 24 * MIB); + const maxEntryBytes = limit("maxEntryBytes", options.maxEntryBytes, MIB); + const maxRawBytes = limit("maxRawBytes", options.maxRawBytes, 32 * MIB); + + // Map order is the LRU order: the first key is the least recently used. + const slots = new Map(); + let bytes = 0; + + function remove(key: string): void { + const slot = slots.get(key); + if (slot) { + slots.delete(key); + bytes -= slot.size; + } + } + + return { + async get(key) { + const slot = slots.get(key); + if (!slot) { + return; + } + if (Date.now() >= slot.expiresAt) { + remove(key); + return; + } + slots.delete(key); + slots.set(key, slot); + return slot.entry; + }, + + async set(key, entry, ttlMs) { + remove(key); + const stored = entry.body.bytes.byteLength; + const size = stored + ENTRY_OVERHEAD_BYTES; + if ( + !(ttlMs > 0) || + stored > maxEntryBytes || + entry.body.rawSize > maxRawBytes || + size > maxBytes + ) { + return; + } + const body = { ...entry.body, bytes: ownBytes(entry.body.bytes) }; + slots.set(key, { + entry: { ...entry, body }, + size, + expiresAt: Date.now() + ttlMs, + }); + bytes += size; + // The new entry is last and fits on its own, so this stops before it. + for (const oldest of slots.keys()) { + if (bytes <= maxBytes) { + break; + } + remove(oldest); + } + }, + + async delete(key) { + remove(key); + }, + + async deleteMatching(identity, urlPrefix) { + for (const [key, slot] of slots) { + if ( + slot.entry.identity === identity && + slot.entry.url.startsWith(urlPrefix) + ) { + remove(key); + } + } + }, + + stats() { + return { entries: slots.size, bytes }; + }, + }; +} diff --git a/packages/http/src/policy.test.ts b/packages/http/src/policy.test.ts new file mode 100644 index 0000000000..ff11e9329c --- /dev/null +++ b/packages/http/src/policy.test.ts @@ -0,0 +1,434 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { identityCodec as codec } from "./body.js"; +import { createMemoryStore } from "./memory-store.js"; +import { + type CacheLookup, + type FreshnessOptions, + lookupResponse, + REVALIDATION_WINDOW_MS, + storeResponse, +} from "./policy.js"; +import type { CacheEntry, CacheStore } from "./store.js"; + +const URL = "https://api.example.com/repos/acme/web/"; +const IDENTITY = "identity-a"; +const KEY = "key-a"; +const MINUTE = 60_000; +const TTL = 5 * MINUTE; +const BODY = { data: [{ id: 1, slug: "frontend" }] }; + +function json( + body: unknown, + headers: Record = {}, + status = 200, +): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json", ...headers }, + }); +} + +function notModified(headers: Record = {}): Response { + return new Response(null, { status: 304, headers }); +} + +async function store( + cache: CacheStore, + response: Response, + freshness: Partial = {}, +): Promise { + return await storeResponse({ + ttlMs: TTL, + ...freshness, + store: cache, + codec, + key: KEY, + identity: IDENTITY, + url: URL, + requestHeaders: {}, + response, + }); +} + +async function lookup( + cache: CacheStore, + freshness: Partial = {}, +): Promise { + return await lookupResponse({ + ttlMs: TTL, + ...freshness, + store: cache, + codec, + key: KEY, + url: URL, + requestHeaders: {}, + }); +} + +/** + * `cache`, but keeping every entry for an hour, so the policy rather than + * the store's expiry decides freshness. + */ +function longLived(cache: CacheStore): CacheStore { + return { ...cache, set: (key, entry) => cache.set(key, entry, 60 * MINUTE) }; +} + +/** A memory store that records the TTL of every `set`. */ +function recordingStore(): CacheStore & { ttls: number[] } { + const inner = createMemoryStore(); + const ttls: number[] = []; + return { + ttls, + get: (key) => inner.get(key), + set: (key, entry, ttlMs) => { + ttls.push(ttlMs); + return inner.set(key, entry, ttlMs); + }, + delete: (key) => inner.delete(key), + deleteMatching: (identity, prefix) => + inner.deleteMatching(identity, prefix), + }; +} + +function expectStale( + result: CacheLookup | undefined, +): Extract { + if (result?.kind !== "stale") { + throw new Error(`expected a stale lookup, got ${result?.kind}`); + } + return result; +} + +beforeEach(() => { + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("storeResponse", () => { + it("stores a response that a hit serves back", async () => { + const cache = createMemoryStore(); + const link = `<${URL}?cursor=0:100:0>; rel="next"`; + const size = await store(cache, json(BODY, { link, "x-other": "kept" })); + expect(size).toBeGreaterThan(0); + + const result = await lookup(cache); + expect(result?.kind).toBe("hit"); + if (result?.kind !== "hit") { + return; + } + expect(result.response.status).toBe(200); + expect(await result.response.json()).toEqual(BODY); + expect(result.response.headers.get("link")).toBe(link); + expect(result.response.headers.get("content-type")).toBe( + "application/json", + ); + expect(result.createdAt).toBe(Date.now()); + expect(result.size).toBe(JSON.stringify(BODY).length); + + const entry = (await cache.get(KEY)) as CacheEntry; + expect(entry).toMatchObject({ + url: URL, + identity: IDENTITY, + headers: { link }, + }); + }); + + it("never persists the authorization token, and still varies on it", async () => { + const cache = createMemoryStore(); + const token = "Bearer secret-token"; + const withToken = (authorization: string) => ({ + ttlMs: TTL, + store: cache, + codec, + key: KEY, + url: URL, + requestHeaders: { authorization }, + }); + await storeResponse({ + ...withToken(token), + identity: IDENTITY, + response: json(BODY, { + "cache-control": "private, max-age=60", + vary: "Authorization", + }), + }); + + const entry = (await cache.get(KEY)) as CacheEntry; + expect(JSON.stringify(entry.policy)).not.toContain("secret-token"); + expect((await lookupResponse(withToken(token)))?.kind).toBe("hit"); + expect( + await lookupResponse(withToken("Bearer other-token")), + ).toBeUndefined(); + }); + + it.each<[string, Response, Partial]>([ + [ + "Cache-Control: no-store", + json(BODY, { "cache-control": "no-store" }), + {}, + ], + ["a non-2xx status", json({ detail: "Not found" }, {}, 404), {}], + ["a zero TTL without a validator", json(BODY), { ttlMs: 0 }], + ])("does not store %s", async (_, response, freshness) => { + const cache = createMemoryStore(); + expect(await store(cache, response, freshness)).toBe(0); + expect(await cache.get(KEY)).toBeUndefined(); + }); + + it("stores any body, and only JSON with requireJson", async () => { + const cache = createMemoryStore(); + const html = () => + new Response("", { + headers: { "content-type": "text/html" }, + }); + expect(await store(cache, html())).toBeGreaterThan(0); + + await cache.delete(KEY); + await expect( + storeResponse({ + ttlMs: TTL, + store: cache, + codec, + key: KEY, + identity: IDENTITY, + url: URL, + requestHeaders: {}, + response: html(), + requireJson: true, + }), + ).rejects.toThrow(SyntaxError); + expect(await cache.get(KEY)).toBeUndefined(); + }); + + it("keeps an entry for the caller's TTL without server directives", async () => { + const cache = recordingStore(); + await store(cache, json(BODY)); + await store(cache, json(BODY), { ttlMs: MINUTE }); + expect(cache.ttls).toEqual([TTL, MINUTE]); + }); + + it("keeps an entry with a validator for the retention window too", async () => { + const cache = recordingStore(); + await store(cache, json(BODY, { etag: '"v1"' })); + await store( + cache, + json(BODY, { "last-modified": new Date().toUTCString() }), + ); + await store( + cache, + json(BODY, { etag: '"v1"', "cache-control": "private, max-age=60" }), + ); + await store(cache, json(BODY, { etag: '"v1"' }), { retainMs: MINUTE }); + expect(cache.ttls).toEqual([ + TTL + REVALIDATION_WINDOW_MS, + TTL + REVALIDATION_WINDOW_MS, + MINUTE + REVALIDATION_WINDOW_MS, + TTL + MINUTE, + ]); + }); + + it("keeps an entry without a validator for the window with staleIfError", async () => { + const cache = recordingStore(); + await store(cache, json(BODY), { staleIfError: true, retainMs: MINUTE }); + expect(cache.ttls).toEqual([TTL + MINUTE]); + }); + + it("caps the server's max-age at the caller's TTL unless maxTtlMs raises it", async () => { + const cache = recordingStore(); + const longLivedResponse = () => + json(BODY, { "cache-control": "private, max-age=3600" }); + await store(cache, longLivedResponse()); + await store(cache, longLivedResponse(), { maxTtlMs: Infinity }); + expect(cache.ttls).toEqual([TTL, 3_600_000]); + }); +}); + +describe("lookupResponse freshness", () => { + it("misses when there is no entry", async () => { + expect(await lookup(createMemoryStore())).toBeUndefined(); + }); + + it("serves an entry without server directives for the caller's TTL", async () => { + const cache = createMemoryStore(); + await store(longLived(cache), json(BODY)); + + vi.setSystemTime(Date.now() + TTL - 1); + expect((await lookup(cache))?.kind).toBe("hit"); + + vi.setSystemTime(Date.now() + 1); + expect(await lookup(cache)).toBeUndefined(); + }); + + it("revalidates every read with a zero TTL", async () => { + const cache = createMemoryStore(); + await store(cache, json(BODY, { etag: '"v1"' }), { ttlMs: 0 }); + expect((await lookup(cache, { ttlMs: 0 }))?.kind).toBe("stale"); + }); + + it("does not let server max-age outlast the caller's TTL", async () => { + const cache = createMemoryStore(); + const response = json(BODY, { + "cache-control": "private, max-age=600", + etag: '"v1"', + }); + await store(cache, response, { ttlMs: 0 }); + expect((await lookup(cache, { ttlMs: 0 }))?.kind).toBe("stale"); + }); + + it("lets server max-age outlast the TTL with maxTtlMs", async () => { + const cache = createMemoryStore(); + const freshness = { ttlMs: MINUTE, maxTtlMs: Infinity }; + await store( + cache, + json(BODY, { "cache-control": "private, max-age=600" }), + freshness, + ); + vi.setSystemTime(Date.now() + 5 * MINUTE); + expect((await lookup(cache, freshness))?.kind).toBe("hit"); + }); + + it("lets server max-age shorten the caller's TTL", async () => { + const cache = createMemoryStore(); + await store( + longLived(cache), + json(BODY, { "cache-control": "private, max-age=60", etag: '"v1"' }), + ); + vi.setSystemTime(Date.now() + 2 * MINUTE); + expect((await lookup(cache))?.kind).toBe("stale"); + }); + + it("treats max-age=0 as stale rather than falling back to the TTL", async () => { + const cache = createMemoryStore(); + await store( + cache, + json(BODY, { "cache-control": "max-age=0", etag: '"v1"' }), + ); + expect((await lookup(cache))?.kind).toBe("stale"); + }); + + it("misses for a body this runtime cannot decode", async () => { + const cache = createMemoryStore(); + await store(cache, json(BODY)); + const entry = (await cache.get(KEY)) as CacheEntry; + await cache.set( + KEY, + { ...entry, body: { ...entry.body, dictId: "unknown" } }, + MINUTE, + ); + expect(await lookup(cache)).toBeUndefined(); + }); + + it("throws for a corrupt policy", async () => { + const cache = createMemoryStore(); + await store(cache, json(BODY)); + const entry = (await cache.get(KEY)) as CacheEntry; + await cache.set(KEY, { ...entry, policy: { v: 999 } }, MINUTE); + await expect(lookup(cache)).rejects.toThrow(); + }); +}); + +describe("lookupResponse revalidation", () => { + async function staleEntry( + cache: CacheStore, + headers: Record = { etag: '"v1"' }, + ): Promise { + await store(cache, json(BODY, headers)); + vi.setSystemTime(Date.now() + TTL + MINUTE); + } + + it("misses for a stale entry without a validator", async () => { + const cache = createMemoryStore(); + await staleEntry(longLived(cache), {}); + expect(await lookup(cache)).toBeUndefined(); + }); + + it("sends If-None-Match and serves the cached body on a matching 304", async () => { + const cache = createMemoryStore(); + await staleEntry(cache); + + const stale = expectStale(await lookup(cache)); + expect(stale.conditionalHeaders).toEqual({ "if-none-match": '"v1"' }); + expect(stale.serveStale).toBeUndefined(); + + const response = await stale.revalidate(notModified({ etag: '"v1"' })); + expect(response?.status).toBe(200); + expect(await response?.json()).toEqual(BODY); + + // The renewed entry is fresh again. + await vi.waitFor(async () => { + expect((await lookup(cache))?.kind).toBe("hit"); + }); + }); + + it("sends If-Modified-Since for an entry with only Last-Modified", async () => { + const cache = createMemoryStore(); + const lastModified = new Date(Date.now() - MINUTE).toUTCString(); + await staleEntry(cache, { "last-modified": lastModified }); + + const stale = expectStale(await lookup(cache)); + expect(stale.conditionalHeaders).toEqual({ + "if-modified-since": lastModified, + }); + const response = await stale.revalidate( + notModified({ "last-modified": lastModified }), + ); + expect(await response?.json()).toEqual(BODY); + }); + + it.each([ + ["a 200", json({ data: [] }, { etag: '"v2"' })], + ["a 304 for another ETag", notModified({ etag: '"v2"' })], + ])("returns undefined for %s", async (_, response) => { + const cache = createMemoryStore(); + await staleEntry(cache); + const stale = expectStale(await lookup(cache)); + expect(await stale.revalidate(response)).toBeUndefined(); + }); + + it("reports a failed renewal and still serves the body", async () => { + const cache = createMemoryStore(); + await staleEntry(cache); + const failure = new Error("disk full"); + const failing: CacheStore = { + ...cache, + set: () => Promise.reject(failure), + }; + const onRenewError = vi.fn(); + + const stale = expectStale( + await lookupResponse({ + ttlMs: TTL, + store: failing, + codec, + key: KEY, + url: URL, + requestHeaders: {}, + onRenewError, + }), + ); + const response = await stale.revalidate(notModified({ etag: '"v1"' })); + expect(await response?.json()).toEqual(BODY); + await vi.waitFor(() => expect(onRenewError).toHaveBeenCalledWith(failure)); + }); +}); + +describe("lookupResponse with staleIfError", () => { + it("returns a stale entry without a validator so it can serve on errors", async () => { + const cache = createMemoryStore(); + const createdAt = Date.now(); + await store(cache, json(BODY), { staleIfError: true }); + vi.setSystemTime(Date.now() + TTL + MINUTE); + + const stale = expectStale(await lookup(cache, { staleIfError: true })); + expect(stale.conditionalHeaders).toEqual({}); + expect(stale.createdAt).toBe(createdAt); + expect(await stale.revalidate(notModified())).toBeUndefined(); + + const response = await stale.serveStale?.(); + expect(response?.status).toBe(200); + expect(await response?.json()).toEqual(BODY); + }); +}); diff --git a/packages/http/src/policy.ts b/packages/http/src/policy.ts new file mode 100644 index 0000000000..04744ec542 --- /dev/null +++ b/packages/http/src/policy.ts @@ -0,0 +1,439 @@ +/** + * HTTP caching decisions for GET responses, through `http-cache-semantics` + * (RFC 9111). The caller's `ttlMs` is how long a response stays fresh, and + * server cache directives can only shorten it, unless the caller raises + * `maxTtlMs`. A stale entry with an `ETag` or `Last-Modified` is kept for a + * retention window and renewed by a matching 304; with `staleIfError`, a + * stale entry is also kept to serve when the server fails. + * + * Works on any `CacheStore` and `BodyCodec` the host passes in, with no Node + * APIs. The host derives the key, decides whether caching is enabled, and + * records telemetry around these calls; `fetchWithCache` does all of it for + * one request. + */ + +import CachePolicy from "http-cache-semantics"; +import type { BodyCodec } from "./body.js"; +import type { CacheEntry, CacheStore } from "./store.js"; + +/** + * How long a stale entry with a validator, or any entry with + * `staleIfError`, is kept after it goes stale, unless the caller sets + * `retainMs`. Bounded by the store's byte budget like any other entry. + */ +export const REVALIDATION_WINDOW_MS: number = 24 * 60 * 60 * 1000; + +/** + * Policy options for a cache scoped to one identity: keys already separate + * users, so `private` responses are storable. + */ +const POLICY_OPTIONS: CachePolicy.Options = { + shared: false, + cacheHeuristic: 0.1, +}; + +/** Response headers kept for callers, such as `Link` for pagination. */ +const PRESERVED_HEADERS = ["link"]; + +/** The validators a conditional request sends. */ +const CONDITIONAL_HEADERS = ["if-none-match", "if-modified-since"]; + +const encoder = new TextEncoder(); + +/** + * How long a cached response is fresh. Shared by lookups and stores, which + * must agree for the same URL. + */ +export type FreshnessOptions = { + /** + * How long a response serves without asking the server. `0` revalidates + * every read. Server cache directives (`max-age`, `no-cache`, `Expires`) + * can shorten it. + */ + ttlMs: number; + /** + * The longest freshness that server directives may give. Defaults to + * `ttlMs`, so a server `max-age` never makes a read skip revalidation for + * longer than the caller allows. Pass `Infinity` to let the server's + * directives win. + */ + maxTtlMs?: number; + /** + * How long an entry is kept after it goes stale, for revalidation and + * `staleIfError`. Defaults to {@link REVALIDATION_WINDOW_MS}. + */ + retainMs?: number; + /** + * Keep stale entries without a validator, and return them from + * `lookupResponse` so the caller can serve one when the server fails. + */ + staleIfError?: boolean; +}; + +/** + * Result of a lookup that found a usable entry. + * + * - `hit`: the entry is fresh; serve `response`. `createdAt` is when the + * response was received, and `size` is the decoded body size in bytes. + * - `stale`: the entry is stale. Send the request with `conditionalHeaders` + * (empty when the entry has no validator), then pass the network response + * to `revalidate`. On a matching 304 it renews the entry and returns the + * cached body; otherwise it returns `undefined` and the network response + * stands (or, for an unusable 304, the caller fetches again without the + * headers). With `staleIfError`, `serveStale` returns the cached body for + * a request that failed. + */ +export type CacheLookup = + | { kind: "hit"; response: Response; createdAt: number; size: number } + | { + kind: "stale"; + conditionalHeaders: Record; + /** When the stale response was received or last revalidated. */ + createdAt: number; + revalidate(response: Response): Promise; + /** Only with `staleIfError`. `undefined` if the body cannot be read. */ + serveStale?: () => Promise; + }; + +export type LookupOptions = FreshnessOptions & { + store: CacheStore; + codec: BodyCodec; + /** From `buildCacheKey`, so the entry is scoped to the identity. */ + key: string; + url: string; + /** Headers of the new request, for `Vary` matching. */ + requestHeaders: Record; + /** Called when renewing a revalidated entry fails; the response stands. */ + onRenewError?: (error: unknown) => void; +}; + +export type StoreOptions = FreshnessOptions & { + store: CacheStore; + codec: BodyCodec; + /** From `buildCacheKey` for the same identity, method, and URL. */ + key: string; + /** Recorded on the entry for identity-scoped invalidation. */ + identity: string; + url: string; + /** Headers the request was sent with, for `Vary` matching. */ + requestHeaders: Record; + /** The response to cache; its body is consumed. */ + response: Response; + /** Store only bodies that parse as JSON, and throw for any other. */ + requireJson?: boolean; +}; + +/** A GET request as `http-cache-semantics` reads it. */ +type GetRequest = { + url: string; + method: "GET"; + headers: Record; +}; + +/** Keep only the response headers callers need. */ +function pickHeaders(headers: Headers): Record { + const result: Record = {}; + for (const name of PRESERVED_HEADERS) { + const value = headers.get(name); + if (value) { + result[name] = value; + } + } + return result; +} + +/** + * Request headers as the policy records them, with `authorization` replaced + * by its SHA-256 digest. `CachePolicy#toObject()` keeps request headers when + * the response has `Vary`, and a store must never hold the token. Lookup and + * store derive the value the same way, so `Vary: Authorization` still tells + * tokens apart. + */ +async function policyRequestHeaders( + headers: Record, +): Promise> { + const result: Record = {}; + for (const [name, value] of Object.entries(headers)) { + result[name] = + name.toLowerCase() === "authorization" && value + ? await sha256Hex(value) + : value; + } + return result; +} + +async function sha256Hex(value: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", encoder.encode(value)); + return Array.from(new Uint8Array(digest), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); +} + +function headersToObject(headers: Headers): Record { + return Object.fromEntries(headers.entries()); +} + +/** + * Whether the server sent `Cache-Control` directives or `Expires`. + * `timeToLive() === 0` alone is ambiguous: it means both "no headers" (use + * the caller's TTL) and "max-age=0" (do not reuse). + */ +function hasServerCacheDirectives(policy: CachePolicy): boolean { + const { rescc, resh } = policy.toObject(); + return Object.keys(rescc).length > 0 || resh["expires"] !== undefined; +} + +/** Whether the stored response has an `ETag` or `Last-Modified`. */ +function hasValidator(policy: CachePolicy): boolean { + const headers = policy.responseHeaders(); + return ( + headers["etag"] !== undefined || headers["last-modified"] !== undefined + ); +} + +/** + * Whether `entry` can be served without revalidation: within the caller's + * TTL, and, when the server sent directives, within theirs too (capped at + * `maxTtlMs`). Server freshness counts only when the request matches the + * stored `Vary` headers. + */ +function isEntryFresh( + policy: CachePolicy, + entry: CacheEntry, + request: GetRequest, + options: FreshnessOptions, +): boolean { + const ageMs = Date.now() - entry.createdAt; + if (!hasServerCacheDirectives(policy)) { + return ageMs < options.ttlMs; + } + const maxTtlMs = options.maxTtlMs ?? options.ttlMs; + return ageMs < maxTtlMs && policy.satisfiesWithoutRevalidation(request); +} + +/** + * How long a store keeps an entry: its freshness lifetime, plus the + * retention window when it has a validator or the caller wants stale + * entries for errors. + */ +function retentionMs(policy: CachePolicy, options: FreshnessOptions): number { + const freshMs = hasServerCacheDirectives(policy) + ? Math.min(policy.timeToLive(), options.maxTtlMs ?? options.ttlMs) + : options.ttlMs; + return hasValidator(policy) || options.staleIfError + ? freshMs + (options.retainMs ?? REVALIDATION_WINDOW_MS) + : freshMs; +} + +/** + * Headers for a response served from `entry`: the policy's computed headers, + * with multiple values joined, plus the preserved headers it lacks. + */ +function buildResponseHeaders( + policy: CachePolicy, + entry: CacheEntry, +): Record { + const result: Record = {}; + for (const [name, value] of Object.entries(policy.responseHeaders())) { + if (value !== undefined) { + result[name] = Array.isArray(value) ? value.join(", ") : value; + } + } + for (const [name, value] of Object.entries(entry.headers)) { + if (!(name in result)) { + result[name] = value; + } + } + return result; +} + +/** + * A decoded body as a `Response` body. TypeScript's DOM `BodyInit` takes + * only `ArrayBuffer`-backed views; stored bodies never sit on a + * `SharedArrayBuffer`. + */ +function responseBody(bytes: Uint8Array): Uint8Array { + return bytes as Uint8Array; +} + +/** The validators to send for a stale entry; empty without one. */ +function conditionalHeaders( + policy: CachePolicy, + request: GetRequest, +): Record { + const headers = policy.revalidationHeaders(request); + const result: Record = {}; + for (const name of CONDITIONAL_HEADERS) { + const value = headers[name]; + if (typeof value === "string") { + result[name] = value; + } + } + return result; +} + +/** + * A `stale` lookup for an entry with a validator or with `staleIfError`, or + * `undefined` for one that is of no use. + */ +function staleLookup( + options: LookupOptions, + entry: CacheEntry, + policy: CachePolicy, + request: GetRequest, +): CacheLookup | undefined { + const validators = conditionalHeaders(policy, request); + const revalidates = Object.keys(validators).length > 0; + if (!revalidates && !options.staleIfError) { + return; + } + const { store, codec, key, onRenewError } = options; + + async function cachedResponse( + responsePolicy: CachePolicy, + ): Promise { + const body = await codec.decode(entry.body); + return body + ? new Response(responseBody(body), { + status: entry.status, + headers: buildResponseHeaders(responsePolicy, entry), + }) + : undefined; + } + + return { + kind: "stale", + conditionalHeaders: validators, + createdAt: entry.createdAt, + async revalidate(response) { + if (!revalidates || response.status !== 304) { + return; + } + const result = policy.revalidatedPolicy(request, { + status: response.status, + headers: headersToObject(response.headers), + }); + // A 304 for a different or missing validator says nothing about + // this entry, so its body cannot be trusted. + if (result.modified || !result.matches) { + return; + } + const cached = await cachedResponse(result.policy); + if (!cached) { + return; + } + + const renewed = { + ...entry, + policy: result.policy.toObject(), + createdAt: Date.now(), + }; + store + .set(key, renewed, retentionMs(result.policy, options)) + .catch((error: unknown) => onRenewError?.(error)); + return cached; + }, + ...(options.staleIfError + ? { serveStale: async () => await cachedResponse(policy) } + : {}), + }; +} + +/** + * Look up a GET request: a fresh entry is a `hit`, and a stale one is + * returned for conditional revalidation or, with `staleIfError`, for + * serving on an error. + * + * @returns The lookup, or `undefined` on a miss: no entry, a stale entry + * without a validator (and no `staleIfError`), or a body this runtime + * cannot decode + * @throws When the stored policy or body is corrupt; the host may drop the + * entry and treat it as a miss + */ +export async function lookupResponse( + options: LookupOptions, +): Promise { + const { store, codec, key, url, requestHeaders } = options; + const entry = await store.get(key); + if (!entry) { + return; + } + + const policy = CachePolicy.fromObject( + entry.policy as CachePolicy.CachePolicyObject, + ); + const request: GetRequest = { + url, + method: "GET", + headers: await policyRequestHeaders(requestHeaders), + }; + if (!isEntryFresh(policy, entry, request, options)) { + return staleLookup(options, entry, policy, request); + } + + const body = await codec.decode(entry.body); + if (!body) { + return; + } + return { + kind: "hit", + response: new Response(responseBody(body), { + status: entry.status, + headers: buildResponseHeaders(policy, entry), + }), + createdAt: entry.createdAt, + size: body.byteLength, + }; +} + +/** + * Store a successful GET response when HTTP caching allows it: not for + * `no-store` or a non-2xx status. The entry is kept for its freshness + * lifetime, plus the retention window with a validator or `staleIfError`. + * + * @returns The stored (encoded) body size in bytes, or 0 when not stored + * @throws With `requireJson`, when the body is not JSON + */ +export async function storeResponse(options: StoreOptions): Promise { + const { store, codec, key, identity, url, requestHeaders, response } = + options; + if (!response.ok) { + return 0; + } + + const policy = new CachePolicy( + { + url, + method: "GET", + headers: await policyRequestHeaders(requestHeaders), + }, + { status: response.status, headers: headersToObject(response.headers) }, + POLICY_OPTIONS, + ); + const ttlMs = retentionMs(policy, options); + if (!policy.storable() || !(ttlMs > 0)) { + return 0; + } + + const raw = new Uint8Array(await response.arrayBuffer()); + if (options.requireJson) { + // Throws for a body that is not JSON. + JSON.parse(new TextDecoder().decode(raw)); + } + const createdAt = Date.now(); + const body = await codec.encode(raw); + await store.set( + key, + { + url, + identity, + status: response.status, + headers: pickHeaders(response.headers), + body, + policy: policy.toObject(), + createdAt, + }, + ttlMs, + ); + return body.bytes.byteLength; +} diff --git a/packages/http/src/retry.test.ts b/packages/http/src/retry.test.ts new file mode 100644 index 0000000000..a94d2b36ad --- /dev/null +++ b/packages/http/src/retry.test.ts @@ -0,0 +1,424 @@ +import { setTimeout as delay } from "node:timers/promises"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + fetchWithRetry, + isIdempotentRequest, + nextRetryDelayMs, + parseRetryAfterMs, + type RetryPolicy, + serverDelayUntil, + sleep, +} from "./retry.js"; + +const NOW = Date.UTC(2026, 0, 1, 12, 0, 0, 300); +const NOW_SECONDS = Math.floor(NOW / 1000); + +const policy: RetryPolicy = { + maxRetries: 2, + baseDelayMs: 250, + maxDelayMs: 2000, + maxTotalDelayMs: 3000, +}; + +describe("parseRetryAfterMs", () => { + it("reads Retry-After in seconds", () => { + expect(parseRetryAfterMs(new Headers({ "Retry-After": "3" }), NOW)).toBe( + 3000, + ); + }); + + it("reads Retry-After as an HTTP-date", () => { + const headers = new Headers({ + "Retry-After": new Date(NOW + 5300).toUTCString(), + }); + + // HTTP-dates drop milliseconds, so this is 12:00:05.000. + expect(parseRetryAfterMs(headers, NOW)).toBe(4700); + }); + + it("returns undefined for a missing or malformed header", () => { + expect(parseRetryAfterMs(new Headers(), NOW)).toBeUndefined(); + expect( + parseRetryAfterMs(new Headers({ "Retry-After": "soon" }), NOW), + ).toBeUndefined(); + }); +}); + +describe("serverDelayUntil", () => { + const target = (NOW_SECONDS + 1) * 1000; + + it("keeps the local estimate without a response Date", () => { + expect(serverDelayUntil(target, new Headers(), NOW)).toBe(700); + }); + + it("measures against the response Date when the local clock is skewed", () => { + const serverNow = NOW + 10 * 60 * 1000; + const headers = new Headers({ Date: new Date(serverNow).toUTCString() }); + + expect( + serverDelayUntil((Math.floor(serverNow / 1000) + 1) * 1000, headers, NOW), + ).toBe(1000); + }); + + it("bounds the delay by the response Date when the local clock lags slightly", () => { + // Local clock 1.5s behind: alone it would put a 1s window 2.2s away. + const headers = new Headers({ Date: new Date(NOW).toUTCString() }); + + expect(serverDelayUntil(target, headers, NOW - 1500)).toBe(1000); + }); + + it("bounds the delay by the response Date when the local clock runs ahead", () => { + const headers = new Headers({ Date: new Date(NOW).toUTCString() }); + + // 2.5s ahead would put the target 1.8s in the past; the Date puts it + // 0-1s away, so the estimate is clamped to the lower bound. + expect(serverDelayUntil(target, headers, NOW + 2500)).toBe(0); + }); + + it("keeps the local estimate when it agrees with the response Date", () => { + const headers = new Headers({ Date: new Date(NOW).toUTCString() }); + + expect(serverDelayUntil(target, headers, NOW)).toBe(700); + }); + + it("treats a target already in the past as no wait", () => { + expect(serverDelayUntil((NOW_SECONDS - 5) * 1000, new Headers(), NOW)).toBe( + 0, + ); + }); +}); + +describe("nextRetryDelayMs", () => { + const base = { + policy, + method: "GET", + status: 429, + serverDelayMs: undefined, + attempt: 0, + waitedMs: 0, + random: () => 0, + }; + + it("waits for the server delay plus jitter of at most half the base step", () => { + expect(nextRetryDelayMs({ ...base, serverDelayMs: 700 })).toBe(700); + expect( + nextRetryDelayMs({ ...base, serverDelayMs: 700, random: () => 1 }), + ).toBe(825); + }); + + it("falls back to equal-jitter exponential backoff", () => { + expect(nextRetryDelayMs({ ...base, attempt: 0 })).toBe(125); + expect(nextRetryDelayMs({ ...base, attempt: 0, random: () => 1 })).toBe( + 250, + ); + expect(nextRetryDelayMs({ ...base, attempt: 1, random: () => 1 })).toBe( + 500, + ); + }); + + it("caps the backoff step at maxDelayMs", () => { + expect( + nextRetryDelayMs({ + ...base, + policy: { ...policy, maxRetries: 10, maxTotalDelayMs: 60_000 }, + attempt: 6, + random: () => 1, + }), + ).toBe(2000); + }); + + it("stops when the server delay exceeds the per-wait cap", () => { + expect( + nextRetryDelayMs({ ...base, serverDelayMs: 30_000 }), + ).toBeUndefined(); + }); + + it("stops when the wait would exceed the total budget", () => { + expect( + nextRetryDelayMs({ + ...base, + attempt: 1, + serverDelayMs: 1000, + waitedMs: 2500, + }), + ).toBeUndefined(); + }); + + it("stops after maxRetries", () => { + expect(nextRetryDelayMs({ ...base, attempt: 2 })).toBeUndefined(); + }); + + it("retries reads in any case", () => { + for (const method of ["GET", "head", "OPTIONS"]) { + expect(nextRetryDelayMs({ ...base, method })).toBe(125); + } + }); + + it("retries a rate-limited write only when the caller maps 429 to any", () => { + const retryableStatuses = new Map([[429, "any" as const]]); + for (const method of ["POST", "PUT", "DELETE"]) { + expect( + nextRetryDelayMs({ ...base, method, status: 429 }), + ).toBeUndefined(); + expect( + nextRetryDelayMs({ ...base, method, status: 429, retryableStatuses }), + ).toBe(125); + } + }); + + it("never retries a write on a 5xx without the idempotent opt-in", () => { + for (const method of ["POST", "PUT", "DELETE"]) { + for (const status of [500, 502, 503, 504]) { + expect(nextRetryDelayMs({ ...base, method, status })).toBeUndefined(); + } + } + expect( + nextRetryDelayMs({ + ...base, + method: "POST", + status: 503, + idempotent: true, + }), + ).toBe(125); + }); + + it("retries a GET on a transient 5xx", () => { + for (const status of [500, 502, 503, 504]) { + expect(nextRetryDelayMs({ ...base, status })).toBe(125); + } + }); + + it("retries a network error or timeout only for idempotent requests", () => { + expect(nextRetryDelayMs({ ...base, status: undefined })).toBe(125); + expect( + nextRetryDelayMs({ ...base, method: "POST", status: undefined }), + ).toBeUndefined(); + expect( + nextRetryDelayMs({ + ...base, + method: "POST", + status: undefined, + idempotent: true, + }), + ).toBe(125); + }); + + it("does not retry deterministic 5xx codes or other 4xx", () => { + for (const status of [400, 404, 501, 505]) { + expect(nextRetryDelayMs({ ...base, status })).toBeUndefined(); + } + }); +}); + +describe("isIdempotentRequest", () => { + it("replays only GET, HEAD, and OPTIONS by default", () => { + for (const method of ["GET", "head", "OPTIONS"]) { + expect(isIdempotentRequest(method)).toBe(true); + } + for (const method of ["POST", "PUT", "PATCH", "DELETE"]) { + expect(isIdempotentRequest(method)).toBe(false); + } + }); + + it("replays any method when the caller opts in", () => { + expect(isIdempotentRequest("POST", true)).toBe(true); + }); +}); + +describe("sleep", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("resolves after the delay", async () => { + const started = performance.now(); + const resolved = vi.fn(); + const promise = sleep(30).then(resolved); + + await delay(0); + expect(resolved).not.toHaveBeenCalled(); + await promise; + expect(resolved).toHaveBeenCalled(); + // Timers may fire up to a millisecond early. + expect(performance.now() - started).toBeGreaterThanOrEqual(29); + }); + + it("rejects with the abort reason as soon as the signal aborts", async () => { + const clear = vi.spyOn(globalThis, "clearTimeout"); + const controller = new AbortController(); + const promise = sleep(60_000, controller.signal); + const reason = new Error("cancelled"); + + controller.abort(reason); + + await expect(promise).rejects.toBe(reason); + expect(clear).toHaveBeenCalledTimes(1); + }); + + it("rejects at once when the signal is already aborted", async () => { + const controller = new AbortController(); + controller.abort(new Error("gone")); + + await expect(sleep(1000, controller.signal)).rejects.toThrow("gone"); + }); +}); + +describe("fetchWithRetry", () => { + const fast: RetryPolicy = { + maxRetries: 2, + baseDelayMs: 2, + maxDelayMs: 50, + maxTotalDelayMs: 100, + }; + + function responses(...items: (Response | Error)[]) { + return vi.fn(async (_attempt: number) => { + const next = items.shift(); + if (!next) { + throw new Error("unexpected request"); + } + if (next instanceof Error) { + throw next; + } + return next; + }); + } + + it("retries a GET after a transient failure and returns the success", async () => { + const send = responses( + new Response(null, { status: 503 }), + new TypeError("fetch failed"), + new Response("ok"), + ); + const onRetry = vi.fn(); + + const response = await fetchWithRetry(send, { + policy: fast, + method: "GET", + onRetry, + }); + + expect(await response.text()).toBe("ok"); + expect(send.mock.calls.map(([attempt]) => attempt)).toEqual([0, 1, 2]); + expect(onRetry.mock.calls.map(([retry]) => retry.status)).toEqual([ + 503, + undefined, + ]); + }); + + it("returns the last failure once retries are used up", async () => { + const send = responses( + new Response(null, { status: 502 }), + new Response(null, { status: 502 }), + new Response(null, { status: 502 }), + ); + + const response = await fetchWithRetry(send, { + policy: fast, + method: "GET", + }); + + expect(response.status).toBe(502); + expect(send).toHaveBeenCalledTimes(3); + }); + + it("does not replay a write the server may have run", async () => { + const send = responses(new Response(null, { status: 503 })); + + const response = await fetchWithRetry(send, { + policy: fast, + method: "POST", + }); + + expect(response.status).toBe(503); + expect(send).toHaveBeenCalledOnce(); + }); + + it("replays an idempotent write", async () => { + const send = responses( + new Response(null, { status: 503 }), + new Response("ok"), + ); + + const response = await fetchWithRetry(send, { + policy: fast, + method: "PUT", + idempotent: true, + }); + + expect(response.status).toBe(200); + }); + + it("waits for Retry-After, and gives up when it exceeds maxDelayMs", async () => { + const onRetry = vi.fn(); + const send = responses( + new Response(null, { status: 429, headers: { "Retry-After": "0" } }), + new Response(null, { status: 429, headers: { "Retry-After": "60" } }), + ); + + const response = await fetchWithRetry(send, { + policy: fast, + method: "GET", + random: () => 0, + onRetry, + }); + + expect(response.status).toBe(429); + expect(onRetry).toHaveBeenCalledWith({ + attempt: 0, + delayMs: 0, + status: 429, + }); + expect(send).toHaveBeenCalledTimes(2); + }); + + it("uses the caller's server delay", async () => { + const serverDelayMs = vi.fn(() => 1); + const send = responses( + new Response(null, { status: 429 }), + new Response("ok"), + ); + + await fetchWithRetry(send, { + policy: fast, + method: "GET", + serverDelayMs, + }); + + expect(serverDelayMs).toHaveBeenCalledOnce(); + }); + + it("throws an error the caller marks as not retryable", async () => { + const failure = new Error("certificate has expired"); + const send = responses(failure); + + await expect( + fetchWithRetry(send, { + policy: fast, + method: "GET", + isRetryableError: (error) => error !== failure, + }), + ).rejects.toBe(failure); + expect(send).toHaveBeenCalledOnce(); + }); + + it("stops waiting when the signal aborts", async () => { + const controller = new AbortController(); + const reason = new Error("cancelled"); + const send = responses(new Response(null, { status: 503 })); + + const pending = fetchWithRetry(send, { + policy: { + ...fast, + baseDelayMs: 10_000, + maxDelayMs: 10_000, + maxTotalDelayMs: 60_000, + }, + method: "GET", + signal: controller.signal, + onRetry: () => controller.abort(reason), + }); + + await expect(pending).rejects.toBe(reason); + }); +}); diff --git a/packages/http/src/retry.ts b/packages/http/src/retry.ts new file mode 100644 index 0000000000..4d5685d62d --- /dev/null +++ b/packages/http/src/retry.ts @@ -0,0 +1,307 @@ +/** + * Retry policy for HTTP requests. Pure logic over standard Web APIs, so it + * runs in Node, Cloudflare Workers, and browsers. `nextRetryDelayMs` decides + * whether to retry and how long to wait; `fetchWithRetry` is a request loop + * built on it for hosts that do not own one. + */ + +/** Caps for one logical request. All delays are in milliseconds. */ +export type RetryPolicy = { + /** Retries after the first attempt. */ + maxRetries: number; + /** First fallback backoff step; it doubles on each retry. */ + baseDelayMs: number; + /** Longest single wait. A server delay above this is not waited for. */ + maxDelayMs: number; + /** Longest total wait across every retry of the request. */ + maxTotalDelayMs: number; +}; + +/** + * Which requests a failed status may replay. + * + * - `any`: the server rejects the request before running it, so replaying + * any method is safe, such as a rate limiter in front of the handler. + * - `idempotent`: the handler may have run, so only GET, HEAD, and OPTIONS + * retry, unless the caller marks the request `idempotent`. + */ +export type RetryReplay = "any" | "idempotent"; + +/** Retried statuses and which requests each may replay. */ +export type RetryableStatuses = ReadonlyMap; + +type HeaderReader = Pick; + +const IDEMPOTENT_METHODS: ReadonlySet = new Set([ + "GET", + "HEAD", + "OPTIONS", +]); + +/** + * The statuses retried when the caller does not pass its own. Other 5xx + * codes (501, 505, ...) are deterministic and are not retried. A server + * that rejects rate-limited requests before running them can map 429 to + * `any`. + */ +export const DEFAULT_RETRYABLE_STATUSES: RetryableStatuses = new Map< + number, + RetryReplay +>([ + [429, "idempotent"], + [500, "idempotent"], + [502, "idempotent"], + [503, "idempotent"], + [504, "idempotent"], +]); + +/** The response `Date` header truncates server time to whole seconds. */ +const DATE_RESOLUTION_MS = 1000; + +/** + * Whether a request may be replayed after the server may have run it: a + * transient 5xx, a network error, or a timeout. True for GET, HEAD, and + * OPTIONS, or when the caller marks the request `idempotent`. + */ +export function isIdempotentRequest( + method: string, + idempotent = false, +): boolean { + return idempotent || IDEMPOTENT_METHODS.has(method.toUpperCase()); +} + +/** + * Whether this failed request may be sent again. With no status (a network + * error or timeout), the server may have run it, so only idempotent + * requests replay. + */ +function isRetryable( + method: string, + status: number | undefined, + idempotent: boolean, + statuses: RetryableStatuses, +): boolean { + const replays = status === undefined ? "idempotent" : statuses.get(status); + if (replays === undefined) { + return false; + } + return replays === "any" || isIdempotentRequest(method, idempotent); +} + +/** + * Milliseconds the response's `Retry-After` (seconds or HTTP-date) asks the + * client to wait, or undefined when it is missing or unusable. + */ +export function parseRetryAfterMs( + headers: HeaderReader, + now: number = Date.now(), +): number | undefined { + const retryAfter = headers.get("retry-after")?.trim(); + if (!retryAfter) { + return undefined; + } + if (/^\d+$/.test(retryAfter)) { + return Number(retryAfter) * 1000; + } + const date = Date.parse(retryAfter); + return Number.isNaN(date) ? undefined : serverDelayUntil(date, headers, now); +} + +/** + * Milliseconds until a server-clock `target` (epoch ms), such as a + * rate-limit reset header. The local clock gives the finest estimate, but + * it may be skewed. The response `Date` bounds the server's clock to + * `[date, date + 1s)`, so the true delay lies in + * `(target - date - 1s, target - date]`; the local estimate is clamped into + * it. + */ +export function serverDelayUntil( + target: number, + headers: HeaderReader, + now: number = Date.now(), +): number { + let delay = target - now; + const date = Date.parse(headers.get("date") ?? ""); + if (!Number.isNaN(date)) { + const latest = target - date; + delay = Math.min(Math.max(delay, latest - DATE_RESOLUTION_MS), latest); + } + return Math.max(0, delay); +} + +/** + * Delay before the next retry, or undefined to stop and surface the error. + * Stops when the method or status is not retryable, the retries are used up, + * the server delay exceeds `maxDelayMs`, or the wait would exceed + * `maxTotalDelayMs`. + */ +export function nextRetryDelayMs({ + policy, + method, + idempotent = false, + status, + serverDelayMs, + attempt, + waitedMs, + retryableStatuses = DEFAULT_RETRYABLE_STATUSES, + random = Math.random, +}: { + policy: RetryPolicy; + method: string; + idempotent?: boolean; + /** Failed response status, or undefined for a network error or timeout. */ + status: number | undefined; + /** The delay the server asked for, such as from `parseRetryAfterMs`. */ + serverDelayMs: number | undefined; + /** Retries already made for this request, starting at 0. */ + attempt: number; + /** Total time already spent waiting for this request. */ + waitedMs: number; + retryableStatuses?: RetryableStatuses; + random?: () => number; +}): number | undefined { + if ( + attempt >= policy.maxRetries || + !isRetryable(method, status, idempotent, retryableStatuses) + ) { + return undefined; + } + + let delayMs: number; + if (serverDelayMs !== undefined) { + if (serverDelayMs > policy.maxDelayMs) { + return undefined; + } + // Spread clients that share a window so they don't all wake at its start. + delayMs = serverDelayMs + random() * (policy.baseDelayMs / 2); + } else { + // Equal jitter: half the step is fixed, half is random. + const step = Math.min(policy.baseDelayMs * 2 ** attempt, policy.maxDelayMs); + delayMs = step / 2 + random() * (step / 2); + } + + return waitedMs + delayMs > policy.maxTotalDelayMs ? undefined : delayMs; +} + +/** Wait `ms`, or reject with the signal's reason as soon as it aborts. */ +export function sleep(ms: number, signal?: AbortSignal | null): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the platform rejects with the signal's own abort reason, often a DOMException or a caller-chosen value, and callers check it verbatim + reject(signal.reason); + return; + } + const onAbort = () => { + clearTimeout(timer); + // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the platform rejects with the signal's own abort reason, often a DOMException or a caller-chosen value, and callers check it verbatim + reject(signal?.reason); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +/** What `fetchWithRetry` reports before it waits for a retry. */ +export type RetryAttempt = { + /** Retries already made, starting at 0. */ + attempt: number; + delayMs: number; + /** The failed status, or undefined when `send` threw. */ + status: number | undefined; + /** What `send` threw, when it threw. */ + error?: unknown; +}; + +export type RetryOptions = { + policy: RetryPolicy; + /** The request method, which decides what may replay. */ + method: string; + /** Mark a write the server dedupes, so it replays like a GET. */ + idempotent?: boolean; + /** Defaults to {@link DEFAULT_RETRYABLE_STATUSES}. */ + retryableStatuses?: RetryableStatuses; + /** + * The delay a failed response asks for. Defaults to `Retry-After`; pass + * one to read a provider's rate-limit reset header too. + */ + serverDelayMs?: (response: Response) => number | undefined; + /** + * Whether an error that `send` threw may be retried. Defaults to every + * error; return false for one that will not change, such as a TLS + * failure. + */ + isRetryableError?: (error: unknown) => boolean; + /** Stops waiting, and rejects with its reason. */ + signal?: AbortSignal; + onRetry?: (retry: RetryAttempt) => void; + random?: () => number; +}; + +/** + * Send a request, and send it again after a retryable failure until the + * policy stops. `send` must build a new request each time, since a request + * body can be read only once. + * + * @returns The last response, which may be a failure the caller handles + * @throws What the last `send` threw, or the signal's reason on abort + */ +export async function fetchWithRetry( + send: (attempt: number) => Promise, + options: RetryOptions, +): Promise { + const { policy, method, idempotent, retryableStatuses, signal } = options; + const serverDelayMs = + options.serverDelayMs ?? + ((response: Response) => parseRetryAfterMs(response.headers)); + const decide = ( + status: number | undefined, + delay: number | undefined, + attempt: number, + waitedMs: number, + ): number | undefined => + nextRetryDelayMs({ + policy, + method, + status, + serverDelayMs: delay, + attempt, + waitedMs, + ...(idempotent === undefined ? {} : { idempotent }), + ...(retryableStatuses === undefined ? {} : { retryableStatuses }), + ...(options.random === undefined ? {} : { random: options.random }), + }); + let waitedMs = 0; + + for (let attempt = 0; ; attempt++) { + let response: Response; + try { + response = await send(attempt); + } catch (error) { + const delayMs = + signal?.aborted || options.isRetryableError?.(error) === false + ? undefined + : decide(undefined, undefined, attempt, waitedMs); + if (delayMs === undefined) { + throw error; + } + options.onRetry?.({ attempt, delayMs, status: undefined, error }); + await sleep(delayMs, signal); + waitedMs += delayMs; + continue; + } + + const delayMs = response.ok + ? undefined + : decide(response.status, serverDelayMs(response), attempt, waitedMs); + if (delayMs === undefined) { + return response; + } + response.body?.cancel().catch(() => undefined); + options.onRetry?.({ attempt, delayMs, status: response.status }); + await sleep(delayMs, signal); + waitedMs += delayMs; + } +} diff --git a/packages/http/src/store.ts b/packages/http/src/store.ts new file mode 100644 index 0000000000..42fc74bf2c --- /dev/null +++ b/packages/http/src/store.ts @@ -0,0 +1,54 @@ +/** + * Storage interface for cached responses. Backends (memory, a filesystem, + * Redis, R2) store entries whose bodies are already encoded by the host's + * `BodyCodec`, and each enforces its own byte budget. + */ + +import type { EncodedBody } from "./body.js"; + +/** A cached response as a store holds it. */ +export type CacheEntry = { + /** Full request URL, matched by {@link CacheStore.deleteMatching}. */ + url: string; + /** Hash of the identity that owns the entry; never a raw credential. */ + identity: string; + /** HTTP status of the cached response. */ + status: number; + /** Response headers kept for callers, such as `Link` for pagination. */ + headers: Readonly>; + /** The response body, encoded by the codec. */ + body: EncodedBody; + /** + * The serialized `http-cache-semantics` policy. Stores keep it as is and + * never read it; `lookupResponse` uses it to decide freshness and + * revalidation. + */ + policy: unknown; + /** When the response was received or last revalidated (epoch ms). */ + createdAt: number; +}; + +/** + * Where cached responses live. Keys come from `buildCacheKey`, so they are + * already scoped to an identity. + */ +export type CacheStore = { + /** The entry under `key`, or `undefined` if it is missing or expired. */ + get(key: string): Promise; + /** + * Store `entry` under `key` for `ttlMs`, replacing any entry already + * there. `ttlMs` is how long the store keeps the entry, not how long it is + * fresh: a stale entry is kept so it can be revalidated or served on an + * error. An entry over the store's limits is not stored, and the one it + * would have replaced is removed, so a later read cannot return the older + * response. + */ + set(key: string, entry: CacheEntry, ttlMs: number): Promise; + /** Remove the entry under `key`, if any. */ + delete(key: string): Promise; + /** + * Remove `identity`'s entries whose URL starts with `urlPrefix`, such as + * the prefixes a mutation invalidates. Other identities' entries are kept. + */ + deleteMatching(identity: string, urlPrefix: string): Promise; +}; diff --git a/packages/http/test/package/check.sh b/packages/http/test/package/check.sh new file mode 100644 index 0000000000..7e6141ca9b --- /dev/null +++ b/packages/http/test/package/check.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Pack @sentry/http, install the tarball into a clean consumer project, and +# typecheck and run that project as ES modules and as CommonJS. The workspace +# imports the TypeScript source; this checks what npm users get instead. +# +# The consumer type-checks with TypeScript 5 and 7, with strict consumer +# options and library checks on, under Node and bundler module resolution. +set -eu + +package_dir=$(cd "$(dirname "$0")/../.." && pwd) +work_dir=$(mktemp -d) +cleanup() { + rm -rf "$work_dir" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +cd "$package_dir" +pnpm run build +pnpm pack --pack-destination "$work_dir" + +for typescript in typescript@^5.8.3 typescript@^7.0.2; do + consumer_dir="$work_dir/consumer-${typescript#typescript@^}" + cp -R "$package_dir/test/package/consumer" "$consumer_dir" + cd "$consumer_dir" + npm install --ignore-scripts --no-audit --no-fund --no-save \ + "$work_dir"/sentry-http-*.tgz "$typescript" @types/node@^22 + npx tsc -p tsconfig.json + npx tsc -p tsconfig.bundler.json + node out/esm.js + node out/cjs.cjs + printf 'Packed @sentry/http works with %s.\n' "$typescript" +done +printf '%s\n' "Packed @sentry/http works from ES modules and CommonJS." diff --git a/packages/http/test/package/consumer/cjs.cts b/packages/http/test/package/consumer/cjs.cts new file mode 100644 index 0000000000..d23195271f --- /dev/null +++ b/packages/http/test/package/consumer/cjs.cts @@ -0,0 +1,8 @@ +// Requires the packed package as CommonJS, as an npm consumer would. +import { strictEqual } from "node:assert"; +import http = require("@sentry/http"); +import codec = require("@sentry/http/codec"); + +strictEqual(http.isIdempotentRequest("get"), true); +strictEqual(http.parseRetryAfterMs(new Headers({ "retry-after": "2" })), 2000); +strictEqual(typeof codec.createBodyCodec().encode, "function"); diff --git a/packages/http/test/package/consumer/esm.ts b/packages/http/test/package/consumer/esm.ts new file mode 100644 index 0000000000..efaa527529 --- /dev/null +++ b/packages/http/test/package/consumer/esm.ts @@ -0,0 +1,40 @@ +// Imports the packed package as ES modules, as an npm consumer would. +import { strictEqual } from "node:assert"; +import { + type CacheStore, + createMemoryStore, + fetchWithCache, + fetchWithRetry, +} from "@sentry/http"; +import { createBodyCodec } from "@sentry/http/codec"; + +const store: CacheStore = createMemoryStore(); +let requests = 0; +const read = () => + fetchWithCache({ + store, + codec: createBodyCodec(), + identity: "consumer", + url: "https://api.example.com/items/", + ttlMs: 60_000, + send: async () => { + requests++; + return await fetchWithRetry( + async () => Response.json({ items: "x".repeat(1024) }), + { + policy: { + maxRetries: 1, + baseDelayMs: 1, + maxDelayMs: 1, + maxTotalDelayMs: 1, + }, + method: "GET", + }, + ); + }, + }); + +await read(); +const cached = (await (await read()).json()) as { items: string }; +strictEqual(cached.items.length, 1024); +strictEqual(requests, 1); diff --git a/packages/http/test/package/consumer/package.json b/packages/http/test/package/consumer/package.json new file mode 100644 index 0000000000..e986b24bba --- /dev/null +++ b/packages/http/test/package/consumer/package.json @@ -0,0 +1,4 @@ +{ + "private": true, + "type": "module" +} diff --git a/packages/http/test/package/consumer/tsconfig.bundler.json b/packages/http/test/package/consumer/tsconfig.bundler.json new file mode 100644 index 0000000000..12c5c7dc5b --- /dev/null +++ b/packages/http/test/package/consumer/tsconfig.bundler.json @@ -0,0 +1,11 @@ +{ + // A bundled app resolves the package's "import" condition without Node's + // module rules. + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "Preserve", + "moduleResolution": "Bundler", + "noEmit": true + }, + "include": ["esm.ts"] +} diff --git a/packages/http/test/package/consumer/tsconfig.json b/packages/http/test/package/consumer/tsconfig.json new file mode 100644 index 0000000000..4f1c055681 --- /dev/null +++ b/packages/http/test/package/consumer/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "target": "ES2022", + "strict": true, + "exactOptionalPropertyTypes": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": false, + "outDir": "out", + "types": ["node"] + }, + "include": ["esm.ts", "cjs.cts"] +} diff --git a/packages/http/tsconfig.browser.json b/packages/http/tsconfig.browser.json new file mode 100644 index 0000000000..4b756ae8d9 --- /dev/null +++ b/packages/http/tsconfig.browser.json @@ -0,0 +1,10 @@ +{ + // The main entry runs without Node APIs: in browsers and Workers. + "extends": "./tsconfig.json", + "compilerOptions": { + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "types": [] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts", "src/codec.ts"] +} diff --git a/packages/http/tsconfig.json b/packages/http/tsconfig.json new file mode 100644 index 0000000000..4c95c16e55 --- /dev/null +++ b/packages/http/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023"], + "module": "ESNext", + "moduleResolution": "Bundler", + "types": ["node"], + "noEmit": true, + "declaration": true, + "isolatedDeclarations": true + }, + "include": ["src/**/*.ts", "tsdown.config.ts"] +} diff --git a/packages/http/tsdown.config.ts b/packages/http/tsdown.config.ts new file mode 100644 index 0000000000..b06d8a669c --- /dev/null +++ b/packages/http/tsdown.config.ts @@ -0,0 +1,21 @@ +import { defineConfig, type UserConfig } from "tsdown"; + +// tsconfig.json checks this file with `isolatedDeclarations`, which needs an +// explicit type on the default export. +const config: UserConfig = defineConfig({ + // `codec` is its own entry: it imports `node:zlib`, and the main entry + // stays portable to browsers and Workers without `nodejs_compat`. + entry: ["src/index.ts", "src/codec.ts"], + format: ["cjs", "esm"], + target: "node22", + platform: "node", + // Keep the published `.js`/`.cjs` and `.d.ts`/`.d.cts` names. + fixedExtension: false, + // `isolatedDeclarations` in tsconfig.json selects the Oxc declaration + // emitter, which needs no TypeScript compiler API. + dts: true, + sourcemap: true, + clean: true, +}); + +export default config; diff --git a/packages/toolkit-core/README.md b/packages/toolkit-core/README.md index 71832e63a7..43b0309bb8 100644 --- a/packages/toolkit-core/README.md +++ b/packages/toolkit-core/README.md @@ -22,16 +22,6 @@ pagination, response cache policy, errors, and endpoint wrappers) is so the CLI, the MCP, and other hosts share one copy. That includes bearer token validation, API URL assembly, and path identifier encoding. -## Response cache codec - -`response-cache/codec` compresses cached response bodies with `node:zlib`, so -it stays here rather than in the portable client: zstd level 3 where the -runtime has it (Node 22.15+, Workers with `nodejs_compat`), brotli quality 4 -otherwise, and no compression below 256 bytes. It implements the client's -`BodyCodec`. Each entry records its encoding and original size; `decode` -returns `undefined` for an entry this runtime cannot read, such as zstd on -older Node, so the caller treats it as a miss. - ## Markdown `markdown` builds Markdown for untrusted values. Pick the helper by what the diff --git a/packages/toolkit-core/package.json b/packages/toolkit-core/package.json index a4cc622b05..56b5494f12 100644 --- a/packages/toolkit-core/package.json +++ b/packages/toolkit-core/package.json @@ -47,10 +47,6 @@ "types": "./src/resource-identity.ts", "default": "./src/resource-identity.ts" }, - "./response-cache/codec": { - "types": "./src/response-cache/codec.ts", - "default": "./src/response-cache/codec.ts" - }, "./search-query": { "types": "./src/search-query.ts", "default": "./src/search-query.ts" diff --git a/packages/toolkit-core/tsconfig.browser.json b/packages/toolkit-core/tsconfig.browser.json index 4e2e72df5a..7efed3f0f5 100644 --- a/packages/toolkit-core/tsconfig.browser.json +++ b/packages/toolkit-core/tsconfig.browser.json @@ -5,5 +5,5 @@ "types": [] }, "include": ["src/**/*.ts"], - "exclude": ["src/**/*.test.ts", "src/test-utils/**", "src/response-cache/codec.ts"] + "exclude": ["src/**/*.test.ts", "src/test-utils/**"] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d31e4395bb..e91bf86d32 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -705,6 +705,9 @@ importers: '@sentry/core': specifier: 'catalog:' version: 11.12.0 + '@sentry/http': + specifier: workspace:* + version: link:../http '@sentry/logger': specifier: workspace:* version: link:../logger @@ -862,6 +865,31 @@ importers: specifier: 'catalog:' version: 7.0.2 + packages/http: + dependencies: + http-cache-semantics: + specifier: ^4.2.0 + version: 4.3.0 + devDependencies: + '@types/http-cache-semantics': + specifier: ^4.2.0 + version: 4.2.0 + '@types/node': + specifier: 'catalog:' + version: 22.20.3 + fast-check: + specifier: ^4.8.0 + version: 4.10.1 + tsdown: + specifier: 'catalog:' + version: 0.23.7(tsrs@7.1.0-beta.tsrs3)(tsx@4.23.13)(typescript@7.0.2) + typescript: + specifier: 'catalog:' + version: 7.0.2 + vitest: + specifier: 'catalog:' + version: 5.0.5(@opentelemetry/api@1.9.1)(@types/node@22.20.3)(@vitest/coverage-v8@5.0.5)(jsdom@28.1.0(supports-color@10.1.0))(msw@2.15.0(@types/node@22.20.3)(typescript@7.0.2))(vite@8.3.8(@types/node@22.20.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) + packages/logger: devDependencies: '@types/node': diff --git a/scripts/tsconfig-policy.test.mjs b/scripts/tsconfig-policy.test.mjs index 1d36a8cc59..727a0bf9ca 100644 --- a/scripts/tsconfig-policy.test.mjs +++ b/scripts/tsconfig-policy.test.mjs @@ -23,6 +23,11 @@ const UNCHECKED = [ reason: "codemod input and expected-output fixtures, compared as text by `jssg test`", }, + { + pattern: /^packages\/http\/test\/package\/consumer\//, + reason: + "packed-package consumer, compiled against the tarball by test/package/check.sh", + }, { pattern: /^packages\/logger\/test\/package\/consumer\//, reason: From 12453d4e39713f89e92406d67141f43742e68e04 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:22:58 +0000 Subject: [PATCH 2/8] feat(http): Add withRetry, and move CLI and MCP retries onto 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 --- packages/cli/src/lib/sentry-client.ts | 51 +++++- packages/http/README.md | 33 ++++ packages/http/src/fetch-retry.test.ts | 172 ++++++++++++++++++ packages/http/src/fetch-retry.ts | 118 ++++++++++++ packages/http/src/index.ts | 11 +- packages/http/src/policy.test.ts | 89 +++++++++ packages/http/src/policy.ts | 82 ++++++--- packages/http/test/package/consumer/esm.ts | 7 +- packages/mcp-core/package.json | 1 + packages/mcp-core/src/api-client/client.ts | 41 +++-- packages/toolkit-core/package.json | 5 + .../toolkit-core/src/sentry-retry.test.ts | 77 ++++++++ packages/toolkit-core/src/sentry-retry.ts | 78 ++++++++ pnpm-lock.yaml | 6 + 14 files changed, 722 insertions(+), 49 deletions(-) create mode 100644 packages/http/src/fetch-retry.test.ts create mode 100644 packages/http/src/fetch-retry.ts create mode 100644 packages/toolkit-core/src/sentry-retry.test.ts create mode 100644 packages/toolkit-core/src/sentry-retry.ts diff --git a/packages/cli/src/lib/sentry-client.ts b/packages/cli/src/lib/sentry-client.ts index 3ed9503260..2188387c52 100644 --- a/packages/cli/src/lib/sentry-client.ts +++ b/packages/cli/src/lib/sentry-client.ts @@ -16,10 +16,15 @@ import { type CredentialRequest, extractUrlPath, getValidatedResponseSource, + parseRetryDelayMs, type ResponseBodyMode, - type RetryPolicy, type TransportCache, } from "@sentry/api/client"; +import type { RetryPolicy } from "@sentry/http"; +import { + TRANSPORT_SENDS_ONCE, + withSentryRetry, +} 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"; @@ -46,6 +51,7 @@ import { } from "./db/auth.js"; import { ApiError, + CliError, HostScopeError, MalformedAuthTokenError, RateLimitError, @@ -89,8 +95,8 @@ const ENDPOINT_TIMEOUT_OVERRIDES: TimeoutOverride[] = [ ]; /** - * Caps for automatic retries. Which statuses and methods retry is the shared - * rule in `@sentry/api/client`. + * Caps for automatic retries. Which statuses and methods retry is Sentry's + * rule in `@sentry/toolkit-core/sentry-retry`. * * `maxDelayMs` caps the jittered backoff and the server-requested wait * (`Retry-After`, rate-limit reset); a longer server-requested wait is not @@ -307,6 +313,15 @@ 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. + */ +function isRetryableError(error: unknown): boolean { + return error instanceof TimeoutError || !(error instanceof CliError); +} + /** Wrap a request in an `http.client` span when the CLI traces HTTP by hand. */ async function withHttpSpan( { method, path }: { method: string; path: string }, @@ -354,8 +369,9 @@ 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. Retries, timeouts, the 401 - * refresh, and redirect validation are in `@sentry/api/client`. + * 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. */ function createCliTransport({ credential, @@ -381,7 +397,7 @@ function createCliTransport({ refresh: refreshAfterUnauthorized, authorization: (current) => formatAuthHeader(current.token), }, - retry: RETRY_POLICY, + retry: TRANSPORT_SENDS_ONCE, timeoutMs: timeoutMs ?? resolveTimeoutMs, fetch: (input, init) => fetchWithCustomTls(input, init, dispatcher), userAgent: getUserAgent(), @@ -408,8 +424,6 @@ function createCliTransport({ buildTlsErrorDetail(error as Error), ) : undefined, - rateLimited: async (response, { path, retryAfterMs }) => - new RateLimitError(path, retryAfterMs, await readErrorDetail(response)), }, cache: responseCache, logger: log, @@ -483,9 +497,20 @@ function createAuthenticatedFetch( const method = init?.method ?? (input instanceof Request ? input.method : "GET"); - return await transport.request(input, init, { + 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, { validateRedirects: options.validatedRedirects === true, idempotent: options.idempotent === true, + // Read before the retry clones `input`: the mode is keyed by the SDK's Request. responseBody: method.toUpperCase() !== "GET" ? "stream" @@ -494,6 +519,14 @@ function createAuthenticatedFetch( : undefined) ?? (options.bufferResponseBody ? "buffer" : "stream")), }); + if (response.status === 429) { + throw new RateLimitError( + path, + parseRetryDelayMs(response.status, response.headers), + await readErrorDetail(response), + ); + } + return response; }; // Every API response, fresh or cached, seeds shell completion, so no API // function has to remember to. Awaited so a command that exits right diff --git a/packages/http/README.md b/packages/http/README.md index 0ad45a34de..6e37a6bee9 100644 --- a/packages/http/README.md +++ b/packages/http/README.md @@ -133,6 +133,39 @@ const response = await fetchWithRetry(() => fetch(url, { method: "POST" }), { `nextRetryDelayMs` is the decision on its own, for hosts with their own loop. +### As a fetch wrapper + +`withRetry` wraps a `fetch` with the same loop. The method and URL come from +the request, a `Request` input is cloned for each attempt, and a stream body +is read once so it can be sent again. An abort from the caller's signal stops +at once. + +```ts +import { withRetry } from "@sentry/http"; + +const retryingFetch = withRetry(fetch, { + policy: { + maxRetries: 2, + baseDelayMs: 250, + maxDelayMs: 5_000, + maxTotalDelayMs: 10_000, + }, + isIdempotent: ({ method, url }) => + method === "PUT" && url.includes("/uploads/"), +}); +``` + +The wrapped function can be a whole client request rather than `fetch`, such +as the transport in `@sentry/api/client`. Each attempt then keeps that +client's timeout, body handling, and credential refresh: + +```ts +const request = withRetry( + (input, init) => transport.request(input, init, { responseBody: "buffer" }), + { policy }, +); +``` + ## License [FSL-1.1-Apache-2.0](LICENSE.md) diff --git a/packages/http/src/fetch-retry.test.ts b/packages/http/src/fetch-retry.test.ts new file mode 100644 index 0000000000..27538b5cda --- /dev/null +++ b/packages/http/src/fetch-retry.test.ts @@ -0,0 +1,172 @@ +import { describe, expect, it, vi } from "vitest"; +import { withRetry } from "./fetch-retry.js"; +import type { RetryPolicy } from "./retry.js"; + +const URL_ = "https://api.example.com/items/"; + +const policy: RetryPolicy = { + maxRetries: 2, + baseDelayMs: 1, + maxDelayMs: 10, + maxTotalDelayMs: 100, +}; + +/** A fetch that answers with each response in turn, and records what it was sent. */ +function scripted(...responses: (() => Response | Promise)[]) { + const sent: { method: string; body: string }[] = []; + const fetch = vi.fn( + async (input: Request | string | URL, init?: RequestInit) => { + const request = new Request(input, init); + sent.push({ method: request.method, body: await request.text() }); + const next = responses.shift(); + if (!next) { + throw new Error("unexpected request"); + } + return await next(); + }, + ); + return { fetch, sent }; +} + +/** A fetch that never answers until its signal aborts. */ +function hanging() { + return vi.fn( + (_input: Request | string | URL, init?: RequestInit) => + new Promise((_, reject) => { + const signal = init?.signal; + // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- mirrors fetch, which rejects with the signal's reason + const abort = () => reject(signal?.reason); + if (signal?.aborted) { + abort(); + } + signal?.addEventListener("abort", abort); + }), + ); +} + +describe("withRetry", () => { + it("retries a transient 503 for a GET and returns the success", async () => { + const { fetch } = scripted( + () => new Response("down", { status: 503 }), + () => new Response("ok"), + ); + const onRetry = vi.fn(); + const retrying = withRetry(fetch, { policy, onRetry }); + + const response = await retrying(URL_); + + expect(await response.text()).toBe("ok"); + expect(fetch).toHaveBeenCalledTimes(2); + expect(onRetry).toHaveBeenCalledWith( + expect.objectContaining({ attempt: 0, status: 503 }), + ); + }); + + it("returns the last failure once the retries are used up", async () => { + const { fetch } = scripted( + ...Array.from( + { length: 3 }, + () => () => new Response("", { status: 502 }), + ), + ); + + const response = await withRetry(fetch, { policy })(URL_); + + expect(response.status).toBe(502); + expect(fetch).toHaveBeenCalledTimes(3); + }); + + it("does not replay a write the handler may have run", async () => { + const { fetch } = scripted(() => new Response("", { status: 503 })); + + const response = await withRetry(fetch, { policy })(URL_, { + method: "POST", + body: "{}", + }); + + expect(response.status).toBe(503); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("replays a write the caller marks idempotent, with its body each time", async () => { + const { fetch, sent } = scripted( + () => new Response("", { status: 503 }), + () => new Response("ok"), + ); + const isIdempotent = vi.fn(() => true); + + await withRetry(fetch, { policy, isIdempotent })( + new Request(URL_, { method: "PUT", body: "payload" }), + ); + + expect(isIdempotent).toHaveBeenCalledWith({ method: "PUT", url: URL_ }); + expect(sent).toEqual([ + { method: "PUT", body: "payload" }, + { method: "PUT", body: "payload" }, + ]); + }); + + it("replays a stream body by reading it once", async () => { + const { fetch, sent } = scripted( + () => new Response("", { status: 500 }), + () => new Response("ok"), + ); + + await withRetry(fetch, { policy, idempotent: true })(URL_, { + method: "POST", + body: new Response("streamed").body, + // Node needs `duplex` for a stream body. + duplex: "half", + }); + + expect(sent.map((request) => request.body)).toEqual([ + "streamed", + "streamed", + ]); + }); + + it("stops at once when the caller aborts", async () => { + const fetch = hanging(); + const controller = new AbortController(); + const reason = new Error("cancelled"); + + const pending = withRetry(fetch, { policy })(URL_, { + signal: controller.signal, + }); + controller.abort(reason); + + await expect(pending).rejects.toBe(reason); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("throws an error the caller marks permanent without retrying", async () => { + const failure = new Error("certificate has expired"); + const fetch = vi.fn(async () => { + throw failure; + }); + + await expect( + withRetry(fetch, { policy, isRetryableError: () => false })(URL_), + ).rejects.toBe(failure); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("waits for the delay the server asks for", async () => { + const { fetch } = scripted( + () => new Response("", { status: 429, headers: { "x-wait-ms": "7" } }), + () => new Response("ok"), + ); + const onRetry = vi.fn(); + + await withRetry(fetch, { + policy, + serverDelayMs: (response) => Number(response.headers.get("x-wait-ms")), + onRetry, + random: () => 0, + })(URL_); + + expect(onRetry).toHaveBeenCalledWith( + expect.objectContaining({ delayMs: 7, status: 429 }), + ); + }); +}); diff --git a/packages/http/src/fetch-retry.ts b/packages/http/src/fetch-retry.ts new file mode 100644 index 0000000000..40cb127c5a --- /dev/null +++ b/packages/http/src/fetch-retry.ts @@ -0,0 +1,118 @@ +/** + * A fetch wrapper that retries, for hosts whose client takes or is a + * `fetch`, such as `@sentry/api`'s transport. + */ + +import { + fetchWithRetry, + parseRetryAfterMs, + type RetryOptions, +} from "./retry.js"; + +/** The `fetch` signature this module wraps and returns. */ +export type FetchLike = ( + input: Request | string | URL, + init?: RequestInit, +) => Promise; + +/** The request {@link RetryingFetchOptions.isIdempotent} is asked about. */ +export type RetryRequest = { method: string; url: string }; + +export type RetryingFetchOptions = Pick< + RetryOptions, + "policy" | "retryableStatuses" | "isRetryableError" | "onRetry" | "random" +> & { + /** + * The delay a failed response asks for. Defaults to `Retry-After`; pass + * one to read a provider's rate-limit reset header too. + */ + serverDelayMs?: (response: Response) => number | undefined; + /** Every request through this fetch is safe to replay, such as a deduped upload. */ + idempotent?: boolean; + /** Writes that are safe to replay, such as a catalog of idempotent operations. */ + isIdempotent?: (request: RetryRequest) => boolean; +}; + +/** + * Wrap `fetch` so failed requests are sent again under `options.policy`. + * A `Request` input is cloned for each attempt and a `ReadableStream` body + * is read once into memory, so the request can be replayed. An abort from + * the caller's signal stops at once. + * + * `fetch` can be a whole client request, such as `@sentry/api`'s + * `transport.request`, so each attempt keeps that client's own timeout, + * body handling, and credential refresh. + * + * @returns A fetch that resolves with the last response, which may be a + * failure the caller handles + */ +export function withRetry( + fetch: FetchLike, + options: RetryingFetchOptions, +): FetchLike { + return async (input, init) => { + const method = ( + init?.method ?? (input instanceof Request ? input.method : "GET") + ).toUpperCase(); + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url; + const idempotent = + options.idempotent === true || + options.isIdempotent?.({ method, url }) === true; + const signal = + init?.signal ?? (input instanceof Request ? input.signal : undefined); + const replay = await replayable(input, init); + + return await fetchWithRetry( + async () => { + const next = replay(); + return await fetch(next.input, next.init); + }, + { + policy: options.policy, + method, + idempotent, + serverDelayMs: + options.serverDelayMs ?? + ((response) => parseRetryAfterMs(response.headers)), + ...(signal ? { signal } : {}), + ...(options.isRetryableError + ? { isRetryableError: options.isRetryableError } + : {}), + ...(options.retryableStatuses + ? { retryableStatuses: options.retryableStatuses } + : {}), + ...(options.onRetry ? { onRetry: options.onRetry } : {}), + ...(options.random ? { random: options.random } : {}), + }, + ); + }; +} + +/** + * A fresh `(input, init)` pair per attempt: `fetch` consumes a body, so a + * retry would otherwise throw `Request body already used`. A `Request` is + * cloned; a `ReadableStream` body, the only single-use body type, is read + * once into a buffer. Other bodies pass through, which keeps the + * `multipart/form-data` boundary `fetch` derives from `FormData`. + */ +async function replayable( + input: Request | string | URL, + init: RequestInit | undefined, +): Promise< + () => { input: Request | string | URL; init: RequestInit | undefined } +> { + if (input instanceof Request) { + return () => ({ input: input.clone(), init }); + } + const body = init?.body; + if (body instanceof ReadableStream) { + const snapshot = await new Response(body).arrayBuffer(); + return () => ({ input, init: { ...init, body: snapshot } }); + } + return () => ({ input, init }); +} diff --git a/packages/http/src/index.ts b/packages/http/src/index.ts index 30166f1f05..4517b6cff2 100644 --- a/packages/http/src/index.ts +++ b/packages/http/src/index.ts @@ -2,8 +2,9 @@ * HTTP response caching and retries over the Fetch API: freshness and * revalidation through `http-cache-semantics`, stale-if-error, identity-scoped * keys, a pluggable `CacheStore` with a byte-budgeted memory store, and - * idempotency-aware retries with backoff and `Retry-After`. No Node APIs; the - * compressing body codec is in `@sentry/http/codec`. + * idempotency-aware retries with backoff and `Retry-After`, as a loop or a + * fetch wrapper. No Node APIs; the compressing body codec is in + * `@sentry/http/codec`. */ export { @@ -13,6 +14,12 @@ export { identityCodec, } from "./body.js"; export { type CachedFetchOptions, fetchWithCache } from "./fetch.js"; +export { + type FetchLike, + type RetryingFetchOptions, + type RetryRequest, + withRetry, +} from "./fetch-retry.js"; export { buildCacheKey, normalizeUrl } from "./keys.js"; export { createMemoryStore, diff --git a/packages/http/src/policy.test.ts b/packages/http/src/policy.test.ts index ff11e9329c..14d7d3cf22 100644 --- a/packages/http/src/policy.test.ts +++ b/packages/http/src/policy.test.ts @@ -432,3 +432,92 @@ describe("lookupResponse with staleIfError", () => { expect(await response?.json()).toEqual(BODY); }); }); + +describe("lookupResponse with Vary", () => { + async function storeVarying( + cache: CacheStore, + vary: string, + requestHeaders: Record, + ): Promise { + await storeResponse({ + ttlMs: TTL, + staleIfError: true, + store: cache, + codec, + key: KEY, + identity: IDENTITY, + url: URL, + requestHeaders, + response: json(BODY, { vary }), + }); + } + + function lookupWith( + cache: CacheStore, + requestHeaders: Record, + ): Promise { + return lookupResponse({ + ttlMs: TTL, + staleIfError: true, + store: cache, + codec, + key: KEY, + url: URL, + requestHeaders, + }); + } + + it("serves an entry without server directives only to a matching request", async () => { + const cache = createMemoryStore(); + await storeVarying(cache, "Accept", { accept: "application/json" }); + + expect( + (await lookupWith(cache, { accept: "application/json" }))?.kind, + ).toBe("hit"); + expect(await lookupWith(cache, { accept: "text/html" })).toBeUndefined(); + }); + + it("does not offer another variant as stale", async () => { + const cache = createMemoryStore(); + await storeVarying(cache, "Accept", { accept: "application/json" }); + vi.setSystemTime(Date.now() + TTL + MINUTE); + + expect(await lookupWith(cache, { accept: "text/html" })).toBeUndefined(); + expect( + (await lookupWith(cache, { accept: "application/json" }))?.kind, + ).toBe("stale"); + }); + + it("matches no request for Vary: *", async () => { + const cache = createMemoryStore(); + await storeVarying(cache, "*", {}); + + expect(await lookupWith(cache, {})).toBeUndefined(); + }); +}); + +describe("null-body statuses", () => { + it("serves a cached 204 with a null body", async () => { + const cache = createMemoryStore(); + await store(cache, new Response(null, { status: 204 })); + + const hit = await lookup(cache); + if (hit?.kind !== "hit") { + throw new Error(`expected a hit, got ${hit?.kind}`); + } + expect(hit.response.status).toBe(204); + expect(hit.response.body).toBeNull(); + }); +}); + +describe("storeResponse body release", () => { + it.each([ + ["Cache-Control: no-store", json(BODY, { "cache-control": "no-store" })], + ["a non-2xx status", json({ detail: "Not found" }, {}, 404)], + ])("cancels the body it does not store for %s", async (_, response) => { + const cancel = vi.spyOn(response.body as ReadableStream, "cancel"); + + expect(await store(createMemoryStore(), response)).toBe(0); + expect(cancel).toHaveBeenCalled(); + }); +}); diff --git a/packages/http/src/policy.ts b/packages/http/src/policy.ts index 04744ec542..9b0f3bae8d 100644 --- a/packages/http/src/policy.ts +++ b/packages/http/src/policy.ts @@ -191,11 +191,28 @@ function hasValidator(policy: CachePolicy): boolean { ); } +/** + * Whether the request has the headers the stored response varies on. A + * response with `Vary: *` matches no request. + */ +function varyMatches(policy: CachePolicy, request: GetRequest): boolean { + const { resh, reqh } = policy.toObject(); + const vary = resh["vary"]; + if (vary === undefined) { + return true; + } + const stored = reqh ?? {}; + return String(vary) + .split(",") + .map((name) => name.trim().toLowerCase()) + .filter(Boolean) + .every((name) => name !== "*" && stored[name] === request.headers[name]); +} + /** * Whether `entry` can be served without revalidation: within the caller's * TTL, and, when the server sent directives, within theirs too (capped at - * `maxTtlMs`). Server freshness counts only when the request matches the - * stored `Vary` headers. + * `maxTtlMs`). */ function isEntryFresh( policy: CachePolicy, @@ -247,13 +264,25 @@ function buildResponseHeaders( return result; } +/** Statuses whose `Response` must have a null body. */ +const NULL_BODY_STATUSES: ReadonlySet = new Set([204, 205, 304]); + /** - * A decoded body as a `Response` body. TypeScript's DOM `BodyInit` takes - * only `ArrayBuffer`-backed views; stored bodies never sit on a - * `SharedArrayBuffer`. + * The response served from `entry` with a decoded body. TypeScript's DOM + * `BodyInit` takes only `ArrayBuffer`-backed views; stored bodies never sit + * on a `SharedArrayBuffer`. */ -function responseBody(bytes: Uint8Array): Uint8Array { - return bytes as Uint8Array; +function cachedResponse( + entry: CacheEntry, + body: Uint8Array, + headers: Record, +): Response { + return new Response( + NULL_BODY_STATUSES.has(entry.status) + ? null + : (body as Uint8Array), + { status: entry.status, headers }, + ); } /** The validators to send for a stale entry; empty without one. */ @@ -289,15 +318,12 @@ function staleLookup( } const { store, codec, key, onRenewError } = options; - async function cachedResponse( + async function decoded( responsePolicy: CachePolicy, ): Promise { const body = await codec.decode(entry.body); return body - ? new Response(responseBody(body), { - status: entry.status, - headers: buildResponseHeaders(responsePolicy, entry), - }) + ? cachedResponse(entry, body, buildResponseHeaders(responsePolicy, entry)) : undefined; } @@ -318,7 +344,7 @@ function staleLookup( if (result.modified || !result.matches) { return; } - const cached = await cachedResponse(result.policy); + const cached = await decoded(result.policy); if (!cached) { return; } @@ -334,7 +360,7 @@ function staleLookup( return cached; }, ...(options.staleIfError - ? { serveStale: async () => await cachedResponse(policy) } + ? { serveStale: async () => await decoded(policy) } : {}), }; } @@ -344,9 +370,9 @@ function staleLookup( * returned for conditional revalidation or, with `staleIfError`, for * serving on an error. * - * @returns The lookup, or `undefined` on a miss: no entry, a stale entry - * without a validator (and no `staleIfError`), or a body this runtime - * cannot decode + * @returns The lookup, or `undefined` on a miss: no entry, a request that + * differs in a header the entry varies on, a stale entry without a + * validator (and no `staleIfError`), or a body this runtime cannot decode * @throws When the stored policy or body is corrupt; the host may drop the * entry and treat it as a miss */ @@ -367,6 +393,10 @@ export async function lookupResponse( method: "GET", headers: await policyRequestHeaders(requestHeaders), }; + // Another variant of the resource: neither fresh nor usable when stale. + if (!varyMatches(policy, request)) { + return; + } if (!isEntryFresh(policy, entry, request, options)) { return staleLookup(options, entry, policy, request); } @@ -377,10 +407,7 @@ export async function lookupResponse( } return { kind: "hit", - response: new Response(responseBody(body), { - status: entry.status, - headers: buildResponseHeaders(policy, entry), - }), + response: cachedResponse(entry, body, buildResponseHeaders(policy, entry)), createdAt: entry.createdAt, size: body.byteLength, }; @@ -398,6 +425,7 @@ export async function storeResponse(options: StoreOptions): Promise { const { store, codec, key, identity, url, requestHeaders, response } = options; if (!response.ok) { + discardBody(response); return 0; } @@ -412,6 +440,7 @@ export async function storeResponse(options: StoreOptions): Promise { ); const ttlMs = retentionMs(policy, options); if (!policy.storable() || !(ttlMs > 0)) { + discardBody(response); return 0; } @@ -437,3 +466,14 @@ export async function storeResponse(options: StoreOptions): Promise { ); return body.bytes.byteLength; } + +/** + * Release a body the cache will not read, so a clone does not buffer the + * whole response while the caller reads the original. Not awaited: + * cancelling one branch of a tee settles only once the other is read. + */ +function discardBody(response: Response): void { + if (response.body && !response.bodyUsed) { + response.body.cancel().catch(() => undefined); + } +} diff --git a/packages/http/test/package/consumer/esm.ts b/packages/http/test/package/consumer/esm.ts index efaa527529..fe32a669a5 100644 --- a/packages/http/test/package/consumer/esm.ts +++ b/packages/http/test/package/consumer/esm.ts @@ -4,7 +4,7 @@ import { type CacheStore, createMemoryStore, fetchWithCache, - fetchWithRetry, + withRetry, } from "@sentry/http"; import { createBodyCodec } from "@sentry/http/codec"; @@ -19,7 +19,7 @@ const read = () => ttlMs: 60_000, send: async () => { requests++; - return await fetchWithRetry( + const retrying = withRetry( async () => Response.json({ items: "x".repeat(1024) }), { policy: { @@ -28,9 +28,10 @@ const read = () => maxDelayMs: 1, maxTotalDelayMs: 1, }, - method: "GET", + retryableStatuses: new Map([[429, "any"]]), }, ); + return await retrying("https://api.example.com/items/"); }, }); diff --git a/packages/mcp-core/package.json b/packages/mcp-core/package.json index 7ebd21c5da..c060074c4f 100644 --- a/packages/mcp-core/package.json +++ b/packages/mcp-core/package.json @@ -195,6 +195,7 @@ "@modelcontextprotocol/server": "catalog:", "@sentry/api": "catalog:", "@sentry/core": "catalog:", + "@sentry/http": "workspace:*", "@sentry/search-syntax": "catalog:", "@sentry/toolkit-core": "workspace:*", "ai": "catalog:", diff --git a/packages/mcp-core/src/api-client/client.ts b/packages/mcp-core/src/api-client/client.ts index ef6aa882bd..115bb413fc 100644 --- a/packages/mcp-core/src/api-client/client.ts +++ b/packages/mcp-core/src/api-client/client.ts @@ -2,6 +2,11 @@ import { getColumnsAndAggregates, isAggregateFieldOrEquation, } from "@sentry/toolkit-core/events-fields"; +import type { RetryPolicy } from "@sentry/http"; +import { + TRANSPORT_SENDS_ONCE, + withSentryRetry, +} from "@sentry/toolkit-core/sentry-retry"; import { type GetOrganizationIssueEventData, getOrganizationIssue, @@ -29,7 +34,6 @@ import { createIdempotentOperationMatcher, nextPageCursor, readJsonResponse, - type RetryPolicy, selectIdempotentWrites, sentryBearerHeader, } from "@sentry/api/client"; @@ -339,8 +343,8 @@ type RequestOptions = { }; /** - * Caps for automatic retries. Which statuses and methods are retried is the - * shared rule in `@sentry/api/client`. + * Caps for automatic retries. Which statuses and methods are retried is + * Sentry's rule in `@sentry/toolkit-core/sentry-retry`. * * Sentry's per-endpoint limits are mostly per second ("Limit is 40 requests * in 1 seconds"), so a 429's reset is usually under a second away and two @@ -355,19 +359,28 @@ const REQUEST_RETRY_POLICY: RetryPolicy = { maxTotalDelayMs: 3000, }; +const isIdempotentOperation = createIdempotentOperationMatcher(() => + selectIdempotentWrites(operations), +); + /** - * Every request goes through the shared transport. `SentryApiService` sets its - * own headers, including Authorization, so the transport only retries; as - * before, it adds no timeout. `fresh` passes on a tool call's `fresh: true`, - * for when the transport gets a cache. + * Every request goes through the shared transport, which sends it once; + * `withSentryRetry` retries around it. `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 = createApiTransport({ - retry: REQUEST_RETRY_POLICY, - fresh: isFreshRead, - isIdempotent: createIdempotentOperationMatcher(() => - selectIdempotentWrites(operations), - ), -}); +const transport = withSentryRetry( + createApiTransport({ + retry: TRANSPORT_SENDS_ONCE, + fresh: isFreshRead, + isIdempotent: isIdempotentOperation, + }), + { + policy: REQUEST_RETRY_POLICY, + isIdempotent: ({ method, url }) => isIdempotentOperation(method, url), + }, +); /** * Default cap for returning attachment bytes inline over the MCP transport. diff --git a/packages/toolkit-core/package.json b/packages/toolkit-core/package.json index 56b5494f12..41515db9b7 100644 --- a/packages/toolkit-core/package.json +++ b/packages/toolkit-core/package.json @@ -59,6 +59,10 @@ "types": "./src/sentry-origin.ts", "default": "./src/sentry-origin.ts" }, + "./sentry-retry": { + "types": "./src/sentry-retry.ts", + "default": "./src/sentry-retry.ts" + }, "./stats-period": { "types": "./src/stats-period.ts", "default": "./src/stats-period.ts" @@ -75,6 +79,7 @@ }, "dependencies": { "@sentry/api": "catalog:", + "@sentry/http": "workspace:*", "@sentry/search-syntax": "catalog:" }, "devDependencies": { diff --git a/packages/toolkit-core/src/sentry-retry.test.ts b/packages/toolkit-core/src/sentry-retry.test.ts new file mode 100644 index 0000000000..b915beb7d7 --- /dev/null +++ b/packages/toolkit-core/src/sentry-retry.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it, vi } from "vitest"; +import { withSentryRetry } from "./sentry-retry"; + +const URL_ = "https://us.sentry.io/api/0/organizations/acme/issues/"; + +const policy = { + maxRetries: 2, + baseDelayMs: 1, + maxDelayMs: 1000, + maxTotalDelayMs: 1000, +}; + +function answering(...statuses: number[]) { + return vi.fn( + async (_input: Request | string | URL, _init?: RequestInit) => + new Response(null, { + status: statuses.shift() ?? 200, + headers: { + "x-sentry-rate-limit-remaining": "0", + "x-sentry-rate-limit-reset": String(Math.floor(Date.now() / 1000)), + }, + }), + ); +} + +describe("withSentryRetry", () => { + it("replays a rate-limited write, since Sentry rejects it before the view runs", async () => { + const request = answering(429); + + const response = await withSentryRetry({ request }, { policy }).request( + URL_, + { + method: "POST", + }, + ); + + expect(response.status).toBe(200); + expect(request).toHaveBeenCalledTimes(2); + }); + + it("does not replay a write after a 5xx", async () => { + const request = answering(503); + + const response = await withSentryRetry({ request }, { policy }).request( + URL_, + { + method: "PUT", + }, + ); + + expect(response.status).toBe(503); + expect(request).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, + }), + ); + + const response = await withSentryRetry({ request }, { policy }).request( + URL_, + { method: "PUT" }, + { idempotent: true }, + ); + + expect(response.status).toBe(200); + expect(request).toHaveBeenCalledTimes(2); + expect(request.mock.calls[1]?.[2]).toEqual({ idempotent: true }); + }); +}); diff --git a/packages/toolkit-core/src/sentry-retry.ts b/packages/toolkit-core/src/sentry-retry.ts new file mode 100644 index 0000000000..6b8c34b22b --- /dev/null +++ b/packages/toolkit-core/src/sentry-retry.ts @@ -0,0 +1,78 @@ +/** + * 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. + */ + +import { + type ApiTransport, + parseRetryDelayMs, + type RetryPolicy, +} from "@sentry/api/client"; +import { + type RetryableStatuses, + type RetryingFetchOptions, + withRetry, +} from "@sentry/http"; + +/** + * Sentry's retried statuses. Its `RatelimitMiddleware` rejects a 429 in + * `process_request`, before the view runs (`sentry/middleware/ratelimit.py`), + * so a 429 replays any method. The handler may have run for a 5xx, so only + * idempotent requests replay. Other 5xx codes (501, 505, ...) are + * deterministic and are not retried. + */ +export const SENTRY_RETRYABLE_STATUSES: RetryableStatuses = new Map([ + [429, "any"], + [500, "idempotent"], + [502, "idempotent"], + [503, "idempotent"], + [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 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. + */ +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 }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e91bf86d32..3f6af18067 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1070,6 +1070,9 @@ importers: '@sentry/core': specifier: 'catalog:' version: 11.12.0 + '@sentry/http': + specifier: workspace:* + version: link:../http '@sentry/search-syntax': specifier: 'catalog:' version: 1.0.0 @@ -1251,6 +1254,9 @@ importers: '@sentry/api': specifier: 'catalog:' version: 2.15.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) + '@sentry/http': + specifier: workspace:* + version: link:../http '@sentry/search-syntax': specifier: 'catalog:' version: 1.0.0 From cc7113c1570790684a49279c6b311cf034a831d8 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:28:27 +0000 Subject: [PATCH 3/8] fix(http): Match Vary headers in any case and replay stream overrides - 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. --- packages/http/src/fetch-retry.test.ts | 21 +++++++++++++++++++++ packages/http/src/fetch-retry.ts | 15 +++++++-------- packages/http/src/policy.test.ts | 10 ++++++++++ packages/http/src/policy.ts | 9 +++++---- 4 files changed, 43 insertions(+), 12 deletions(-) diff --git a/packages/http/src/fetch-retry.test.ts b/packages/http/src/fetch-retry.test.ts index 27538b5cda..ae7f2d6006 100644 --- a/packages/http/src/fetch-retry.test.ts +++ b/packages/http/src/fetch-retry.test.ts @@ -125,6 +125,27 @@ describe("withRetry", () => { ]); }); + it("replays a stream body that overrides a Request input's body", async () => { + const { fetch, sent } = scripted( + () => new Response("", { status: 500 }), + () => new Response("ok"), + ); + + await withRetry(fetch, { policy, idempotent: true })( + new Request(URL_, { method: "POST", body: "original" }), + { + body: new Response("override").body, + // Node needs `duplex` for a stream body. + duplex: "half", + }, + ); + + expect(sent.map((request) => request.body)).toEqual([ + "override", + "override", + ]); + }); + it("stops at once when the caller aborts", async () => { const fetch = hanging(); const controller = new AbortController(); diff --git a/packages/http/src/fetch-retry.ts b/packages/http/src/fetch-retry.ts index 40cb127c5a..4a1d82b10d 100644 --- a/packages/http/src/fetch-retry.ts +++ b/packages/http/src/fetch-retry.ts @@ -106,13 +106,12 @@ async function replayable( ): Promise< () => { input: Request | string | URL; init: RequestInit | undefined } > { - if (input instanceof Request) { - return () => ({ input: input.clone(), init }); - } const body = init?.body; - if (body instanceof ReadableStream) { - const snapshot = await new Response(body).arrayBuffer(); - return () => ({ input, init: { ...init, body: snapshot } }); - } - return () => ({ input, init }); + const nextInit = + body instanceof ReadableStream + ? { ...init, body: await new Response(body).arrayBuffer() } + : init; + return input instanceof Request + ? () => ({ input: input.clone(), init: nextInit }) + : () => ({ input, init: nextInit }); } diff --git a/packages/http/src/policy.test.ts b/packages/http/src/policy.test.ts index 14d7d3cf22..cef4f92c4b 100644 --- a/packages/http/src/policy.test.ts +++ b/packages/http/src/policy.test.ts @@ -488,6 +488,16 @@ describe("lookupResponse with Vary", () => { ).toBe("stale"); }); + it("matches request header names in any case", async () => { + const cache = createMemoryStore(); + await storeVarying(cache, "Accept", { Accept: "application/json" }); + + expect( + (await lookupWith(cache, { ACCEPT: "application/json" }))?.kind, + ).toBe("hit"); + expect(await lookupWith(cache, { Accept: "text/html" })).toBeUndefined(); + }); + it("matches no request for Vary: *", async () => { const cache = createMemoryStore(); await storeVarying(cache, "*", {}); diff --git a/packages/http/src/policy.ts b/packages/http/src/policy.ts index 9b0f3bae8d..3b42b7d70b 100644 --- a/packages/http/src/policy.ts +++ b/packages/http/src/policy.ts @@ -153,11 +153,12 @@ async function policyRequestHeaders( headers: Record, ): Promise> { const result: Record = {}; - for (const [name, value] of Object.entries(headers)) { + // Lowercase names, as `http-cache-semantics` stores them and `Vary` + // matching compares them. + for (const [rawName, value] of Object.entries(headers)) { + const name = rawName.toLowerCase(); result[name] = - name.toLowerCase() === "authorization" && value - ? await sha256Hex(value) - : value; + name === "authorization" && value ? await sha256Hex(value) : value; } return result; } From 8f0485f27d9d0fd6459aa7f158a05a9e88bf7e21 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:35:39 +0000 Subject: [PATCH 4/8] fix(http): Keep the caller's TTL for Cache-Control without freshness 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. --- packages/http/README.md | 4 ++-- packages/http/src/policy.test.ts | 10 ++++++++++ packages/http/src/policy.ts | 18 ++++++++++++++---- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/packages/http/README.md b/packages/http/README.md index 6e37a6bee9..13b0ae07c3 100644 --- a/packages/http/README.md +++ b/packages/http/README.md @@ -40,8 +40,8 @@ const response = await fetchWithCache({ - `ttlMs` is how long a response serves without a request. `0` revalidates every read. -- Server cache headers (`Cache-Control`, `Expires`) can only shorten `ttlMs`, - never extend it, so a server `max-age` cannot make a read skip revalidation +- Server freshness headers (`Cache-Control: max-age` or `no-cache`, and + `Expires`) can only shorten `ttlMs`, never extend it, so a server `max-age` cannot make a read skip revalidation longer than you allow. Set `maxTtlMs` to let the server's headers give more, such as `Infinity` to follow them. - A stale entry with a validator stays in the store for `retainMs` (24 hours by diff --git a/packages/http/src/policy.test.ts b/packages/http/src/policy.test.ts index cef4f92c4b..0b2c46ad3b 100644 --- a/packages/http/src/policy.test.ts +++ b/packages/http/src/policy.test.ts @@ -300,6 +300,16 @@ describe("lookupResponse freshness", () => { expect((await lookup(cache))?.kind).toBe("stale"); }); + it("uses the caller's TTL when Cache-Control sets no freshness", async () => { + const cache = createMemoryStore(); + expect( + await store(cache, json(BODY, { "cache-control": "private" })), + ).toBeGreaterThan(0); + + vi.setSystemTime(Date.now() + TTL - 1); + expect((await lookup(cache))?.kind).toBe("hit"); + }); + it("treats max-age=0 as stale rather than falling back to the TTL", async () => { const cache = createMemoryStore(); await store( diff --git a/packages/http/src/policy.ts b/packages/http/src/policy.ts index 3b42b7d70b..aaf3ab3737 100644 --- a/packages/http/src/policy.ts +++ b/packages/http/src/policy.ts @@ -175,13 +175,23 @@ function headersToObject(headers: Headers): Record { } /** - * Whether the server sent `Cache-Control` directives or `Expires`. - * `timeToLive() === 0` alone is ambiguous: it means both "no headers" (use - * the caller's TTL) and "max-age=0" (do not reuse). + * `Cache-Control` directives that set a private cache's freshness. Others, + * such as `private`, only say who may store the response. + */ +const FRESHNESS_DIRECTIVES = ["max-age", "no-cache"] as const; + +/** + * Whether the server set the response's freshness, with `max-age`, + * `no-cache`, or `Expires`. `timeToLive() === 0` alone is ambiguous: it + * means both "no freshness headers" (use the caller's TTL) and "max-age=0" + * (do not reuse). */ function hasServerCacheDirectives(policy: CachePolicy): boolean { const { rescc, resh } = policy.toObject(); - return Object.keys(rescc).length > 0 || resh["expires"] !== undefined; + return ( + FRESHNESS_DIRECTIVES.some((name) => name in rescc) || + resh["expires"] !== undefined + ); } /** Whether the stored response has an `ETag` or `Last-Modified`. */ From 1227efd6586bb226aa7fe73d45b1f5dcec58ba94 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:16:09 +0000 Subject: [PATCH 5/8] build: Release npm libraries without per-package workflow edits - `.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. --- .craft.yml | 18 ++-- .github/workflows/merge-jobs.yml | 112 +++++++++++++++++++----- .github/workflows/release.yml | 38 ++------ docs/operations/github-actions.md | 16 ++++ package.json | 2 +- packages/http/LICENSE | 21 +++++ packages/http/LICENSE.md | 105 ---------------------- packages/http/README.md | 2 +- packages/http/package.json | 6 +- scripts/npm-library-workspaces.mjs | 54 ++++++++++++ scripts/npm-library-workspaces.test.mjs | 27 ++++++ 11 files changed, 225 insertions(+), 176 deletions(-) create mode 100644 packages/http/LICENSE delete mode 100644 packages/http/LICENSE.md create mode 100644 scripts/npm-library-workspaces.mjs create mode 100644 scripts/npm-library-workspaces.test.mjs diff --git a/.craft.yml b/.craft.yml index 3fb2501910..60f1aa4b2e 100644 --- a/.craft.yml +++ b/.craft.yml @@ -133,18 +133,12 @@ workspaces: assert_match version.to_s, shell_output("#{bin}/sentry --version").chomp end end - # No preReleaseCommand: Craft bumps package.json through the npm target. - packages/http: - changelog: - policy: auto - releaseBranchPrefix: "release/{{workspaceName}}" - targets: - - name: github - tagPrefix: "{{workspaceName}}@" - includeNames: '/^{{packageSimpleName}}-\d.*\.tgz$/' - - name: npm - includeNames: '/^{{packageSimpleName}}-\d.*\.tgz$/' - packages/logger: + # Standalone npm libraries. Each is released on its own, with + # `@` tags and `release//` branches, and + # `merge-jobs.yml` packs every one of them. To publish another package + # from `packages/`, add its directory name here. No preReleaseCommand: + # Craft bumps package.json through the npm target. + packages/{http,logger}: changelog: policy: auto releaseBranchPrefix: "release/{{workspaceName}}" diff --git a/.github/workflows/merge-jobs.yml b/.github/workflows/merge-jobs.yml index dd6f2f4adb..0e50e44c81 100644 --- a/.github/workflows/merge-jobs.yml +++ b/.github/workflows/merge-jobs.yml @@ -2,31 +2,36 @@ name: Post-merge tasks on: push: - branches: ["main", "release/*", "release/http/**", "release/logger/**"] + # The CLI's release branches are built by cli-build.yml. + branches: ["main", "release/**", "!release/cli/**"] workflow_dispatch: +permissions: + contents: read + jobs: - build-publish: + test: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false - name: Setup pnpm uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version-file: "package.json" - cache: "pnpm" - name: Install dependencies run: pnpm install - name: Build - run: pnpm --filter '@sentry/mcp-core...' --filter @sentry/http --filter @sentry/logger --if-present run build + run: pnpm --filter '@sentry/mcp-core...' --filter @sentry/logger --if-present run build - name: Run linter run: pnpm lint @@ -34,25 +39,88 @@ jobs: - name: Run tests run: pnpm test:ci - - name: Package http - working-directory: packages/http - run: pnpm pack --pack-destination dist - - - name: Package logger - working-directory: packages/logger - run: pnpm pack --pack-destination dist - - - name: Archive artifacts - uses: actions/upload-artifact@v4 - with: - name: ${{ github.sha }} - path: | - ${{ github.workspace }}/packages/http/dist/*.tgz - ${{ github.workspace }}/packages/logger/dist/*.tgz - - name: Publish Test Report uses: mikepenz/action-junit-report@cf701569b05ccdd861a76b8607a66d76f6fd4857 if: ${{ !cancelled() }} with: report_paths: "**/*.junit.xml" comment: false + + # Every Craft workspace without its own artifact provider is an npm + # library whose tarball this workflow builds. + discover-packages: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.packages.outputs.matrix }} + + steps: + - name: Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: "package.json" + + # The same major version as release.yml's getsentry/craft@v3. + - name: Install Craft + run: npm install --global @sentry/craft@3 # zizmor: ignore[adhoc-packages] + + - name: List packages + id: packages + run: node scripts/npm-library-workspaces.mjs + + package: + needs: discover-packages + runs-on: ubuntu-latest + strategy: + matrix: ${{ fromJSON(needs.discover-packages.outputs.matrix) }} + name: Package ${{ matrix.name }} + + steps: + - name: Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - name: Setup pnpm + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: "package.json" + + - name: Install dependencies + run: pnpm install + + - name: Build + env: + WORKSPACE: ${{ matrix.workspace }} + run: pnpm --filter "{./$WORKSPACE}..." --if-present run build + + - name: Package + working-directory: ${{ matrix.workspace }} + run: pnpm pack --pack-destination dist + + - name: Upload tarball + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: npm-${{ matrix.name }} + path: ${{ matrix.workspace }}/dist/*.tgz + if-no-files-found: error + + # Craft reads every tarball from one artifact named after the commit. + archive: + needs: [test, package] + runs-on: ubuntu-latest + + steps: + - name: Archive artifacts + uses: actions/upload-artifact/merge@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: ${{ github.sha }} + pattern: npm-* + delete-merged: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23d814a5b3..651dece236 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,14 +4,10 @@ on: workflow_dispatch: inputs: product: - description: Product to release + description: "Package to release: a directory under packages/ with a .craft.yml workspace, such as cli, http, or logger" required: true - type: choice + type: string default: cli - options: - - cli - - http - - logger bump: description: "Version bump: auto (from commits), pre (next prerelease), or an explicit bump type" required: true @@ -62,37 +58,15 @@ jobs: with: run_install: false - - name: Resolve release workspace - id: release - env: - PRODUCT: ${{ inputs.product }} - run: | - # Each product maps to a `.craft.yml` workspace. The `cli` release - # also publishes @sentry/mcp-server at the same version. - case "$PRODUCT" in - cli) - workspace=packages/cli - ;; - http) - workspace=packages/http - ;; - logger) - workspace=packages/logger - ;; - *) - echo "::error::Unsupported product: $PRODUCT" - exit 1 - ;; - esac - - echo "workspace=$workspace" >> "$GITHUB_OUTPUT" - - name: Prepare release uses: getsentry/craft@v3 env: GITHUB_TOKEN: ${{ steps.token.outputs.token }} with: - workspace: ${{ steps.release.outputs.workspace }} + # Craft fails, listing the workspaces it has, for any other name. + # The `cli` release also publishes @sentry/mcp-server at the same + # version. + workspace: packages/${{ inputs.product }} # An exact version wins over the bump. Craft bumps from the # workspace's latest release tag, or from its package.json version # before the first tag. diff --git a/docs/operations/github-actions.md b/docs/operations/github-actions.md index 1d31d20c44..6706f2499f 100644 --- a/docs/operations/github-actions.md +++ b/docs/operations/github-actions.md @@ -154,6 +154,22 @@ token pushes the branch and opens the PR, so `test.yml` runs on it. branch by hand are lost. - The PR is never merged automatically. +### release.yml and merge-jobs.yml + +`release.yml` prepares a release of one package with Craft. Its `product` input +is a directory under `packages/`, such as `cli`, `http`, or `logger`, and Craft +fails for a directory that has no `.craft.yml` workspace. + +`merge-jobs.yml` runs on `main` and on every release branch except the CLI's. +It lists the Craft workspaces that use the default artifact provider with +`scripts/npm-library-workspaces.mjs`, packs each one in a parallel matrix job, +and merges the tarballs into the artifact named after the commit, where Craft +reads them. The CLI sets its own artifact provider and is built by +`cli-build.yml`. + +To publish another package from `packages/`, add its directory name to the +`packages/{...}` workspace key in `.craft.yml`. Neither workflow needs a change. + ## Package CI checks Add a check for one workspace package to that package's `package.json`, not to diff --git a/package.json b/package.json index b8bad5a16f..86bbc0bf07 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ }, "scripts": { "docs:check": "node scripts/check-doc-links.mjs", - "test:ci-projects": "node --test scripts/ci-projects.test.mjs scripts/check-workspace-deps.test.mjs scripts/cli-nightly-version.test.mjs scripts/cli-nightly-watchdog.test.mjs scripts/platform-setup-pr.test.mjs scripts/codemod-version-changed.test.mjs scripts/cloudflare-deployment.test.mjs scripts/deploy-workflow.test.mjs scripts/migrate-cloudflare-token.test.mjs scripts/oxc-config.test.mjs scripts/cli-lint-rules.test.mjs scripts/workflow-policy.test.mjs scripts/tsconfig-policy.test.mjs", + "test:ci-projects": "node --test scripts/ci-projects.test.mjs scripts/check-workspace-deps.test.mjs scripts/cli-nightly-version.test.mjs scripts/cli-nightly-watchdog.test.mjs scripts/platform-setup-pr.test.mjs scripts/codemod-version-changed.test.mjs scripts/npm-library-workspaces.test.mjs scripts/cloudflare-deployment.test.mjs scripts/deploy-workflow.test.mjs scripts/migrate-cloudflare-token.test.mjs scripts/oxc-config.test.mjs scripts/cli-lint-rules.test.mjs scripts/workflow-policy.test.mjs scripts/tsconfig-policy.test.mjs", "dev": "pnpm --filter '@sentry/mcp-cloudflare...' --if-present run build && dotenv -e .env -e .env.local -- pnpm --parallel --filter @sentry/mcp-cloudflare --filter @sentry/mcp-core --filter @sentry/mcp-server-mocks --if-present run dev", "dev:stdio": "pnpm --filter '@sentry/mcp-core...' --if-present run build 1>&2 && dotenv -e .env -e .env.local -- pnpm --silent --dir packages/cli run cli mcp", "build": "dotenv -e .env -e .env.local -- pnpm -r --filter '!sentry' --filter '!sentry-cli-docs' --if-present run build", diff --git a/packages/http/LICENSE b/packages/http/LICENSE new file mode 100644 index 0000000000..09e7c6f7d9 --- /dev/null +++ b/packages/http/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Functional Software, Inc. dba Sentry + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/http/LICENSE.md b/packages/http/LICENSE.md deleted file mode 100644 index 6e9bafc7ac..0000000000 --- a/packages/http/LICENSE.md +++ /dev/null @@ -1,105 +0,0 @@ -# Functional Source License, Version 1.1, Apache 2.0 Future License - -## Abbreviation - -FSL-1.1-Apache-2.0 - -## Notice - -Copyright 2025 Functional Software, Inc. dba Sentry - -## Terms and Conditions - -### Licensor ("We") - -The party offering the Software under these Terms and Conditions. - -### The Software - -The "Software" is each version of the software that we make available under -these Terms and Conditions, as indicated by our inclusion of these Terms and -Conditions with the Software. - -### License Grant - -Subject to your compliance with this License Grant and the Patents, -Redistribution and Trademark clauses below, we hereby grant you the right to -use, copy, modify, create derivative works, publicly perform, publicly display -and redistribute the Software for any Permitted Purpose identified below. - -### Permitted Purpose - -A Permitted Purpose is any purpose other than a Competing Use. A Competing Use -means making the Software available to others in a commercial product or -service that: - -1. substitutes for the Software; - -2. substitutes for any other product or service we offer using the Software - that exists as of the date we make the Software available; or - -3. offers the same or substantially similar functionality as the Software. - -Permitted Purposes specifically include using the Software: - -1. for your internal use and access; - -2. for non-commercial education; - -3. for non-commercial research; and - -4. in connection with professional services that you provide to a licensee - using the Software in accordance with these Terms and Conditions. - -### Patents - -To the extent your use for a Permitted Purpose would necessarily infringe our -patents, the license grant above includes a license under our patents. If you -make a claim against any party that the Software infringes or contributes to -the infringement of any patent, then your patent license to the Software ends -immediately. - -### Redistribution - -The Terms and Conditions apply to all copies, modifications and derivatives of -the Software. - -If you redistribute any copies, modifications or derivatives of the Software, -you must include a copy of or a link to these Terms and Conditions and not -remove any copyright notices provided in or with the Software. - -### Disclaimer - -THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR -PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT. - -IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE -SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, -EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE. - -### Trademarks - -Except for displaying the License Details and identifying us as the origin of -the Software, you have no right under these Terms and Conditions to use our -trademarks, trade names, service marks or product names. - -## Grant of Future License - -We hereby irrevocably grant you an additional license to use the Software under -the Apache License, Version 2.0 that is effective on the second anniversary of -the date we make the Software available. On or after that date, you may use the -Software under the Apache License, Version 2.0, in which case the following -will apply: - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. - -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software distributed -under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. diff --git a/packages/http/README.md b/packages/http/README.md index 13b0ae07c3..5a30cea31b 100644 --- a/packages/http/README.md +++ b/packages/http/README.md @@ -168,4 +168,4 @@ const request = withRetry( ## License -[FSL-1.1-Apache-2.0](LICENSE.md) +[MIT](LICENSE) diff --git a/packages/http/package.json b/packages/http/package.json index ee159ea7b1..75a997d01d 100644 --- a/packages/http/package.json +++ b/packages/http/package.json @@ -1,9 +1,9 @@ { "name": "@sentry/http", - "version": "0.1.0-dev.0", + "version": "1.0.0-dev.0", "description": "HTTP response caching, body compression, and retries over the Fetch API, with pluggable cache stores", "type": "module", - "license": "FSL-1.1-Apache-2.0", + "license": "MIT", "author": "Sentry", "homepage": "https://github.com/getsentry/toolkit/tree/main/packages/http#readme", "keywords": [ @@ -31,7 +31,7 @@ }, "files": [ "dist", - "LICENSE.md", + "LICENSE", "README.md" ], "exports": { diff --git a/scripts/npm-library-workspaces.mjs b/scripts/npm-library-workspaces.mjs new file mode 100644 index 0000000000..082e432cbf --- /dev/null +++ b/scripts/npm-library-workspaces.mjs @@ -0,0 +1,54 @@ +/** + * Lists the Craft release workspaces that `merge-jobs.yml` packs. + * + * Craft's default artifact provider reads the tarballs from the artifact + * that `merge-jobs.yml` uploads for the release commit. A workspace that + * sets its own `artifactProvider`, like the CLI, is built elsewhere. So the + * packages to pack are the workspaces without one, and publishing another + * package needs only its `.craft.yml` entry. + * + * Writes `matrix={"include":[{"workspace":"packages/http","name":"http"}]}` + * to `$GITHUB_OUTPUT`, or prints the matrix when that is unset. + */ +import { execFileSync } from "node:child_process"; +import { appendFileSync } from "node:fs"; +import { posix } from "node:path"; +import { pathToFileURL } from "node:url"; + +/** + * The matrix of workspaces that use the default artifact provider. + * + * @param {string[]} workspaces Concrete workspace paths, from + * `craft workspace list`. + * @param {(workspace: string) => Record} resolveConfig The + * workspace's resolved configuration, from `craft config --workspace`. + */ +export function libraryMatrix(workspaces, resolveConfig) { + const include = workspaces + .filter( + (workspace) => resolveConfig(workspace).artifactProvider === undefined, + ) + .map((workspace) => ({ workspace, name: posix.basename(workspace) })); + if (include.length === 0) { + throw new Error("No Craft workspace uses the default artifact provider"); + } + return { include }; +} + +function craftJson(craft, args) { + return JSON.parse(execFileSync(craft, args, { encoding: "utf8" })); +} + +if (import.meta.url === pathToFileURL(process.argv[1]).href) { + const craft = process.env.CRAFT_BIN || "craft"; + const matrix = libraryMatrix( + craftJson(craft, ["workspace", "list"]), + (workspace) => craftJson(craft, ["config", "--workspace", workspace]), + ); + const json = JSON.stringify(matrix); + if (process.env.GITHUB_OUTPUT) { + appendFileSync(process.env.GITHUB_OUTPUT, `matrix=${json}\n`); + } else { + process.stdout.write(`${json}\n`); + } +} diff --git a/scripts/npm-library-workspaces.test.mjs b/scripts/npm-library-workspaces.test.mjs new file mode 100644 index 0000000000..4f71b53676 --- /dev/null +++ b/scripts/npm-library-workspaces.test.mjs @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { libraryMatrix } from "./npm-library-workspaces.mjs"; + +const configs = { + "packages/cli": { artifactProvider: { name: "github" } }, + "packages/http": {}, + "packages/logger": {}, +}; + +test("lists workspaces that use the default artifact provider", () => { + assert.deepEqual( + libraryMatrix(Object.keys(configs), (workspace) => configs[workspace]), + { + include: [ + { workspace: "packages/http", name: "http" }, + { workspace: "packages/logger", name: "logger" }, + ], + }, + ); +}); + +test("fails when there is nothing to pack", () => { + assert.throws(() => + libraryMatrix(["packages/cli"], () => configs["packages/cli"]), + ); +}); From 3aa1fab3372ec33f7642ed6f7549aa9802931580 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:19:45 +0000 Subject: [PATCH 6/8] fix(ci): Let the merge-jobs test job publish its JUnit check run The workflow-level `contents: read` dropped `checks: write`, which `mikepenz/action-junit-report` needs to create its check run. --- .github/workflows/merge-jobs.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/merge-jobs.yml b/.github/workflows/merge-jobs.yml index 0e50e44c81..866b23a514 100644 --- a/.github/workflows/merge-jobs.yml +++ b/.github/workflows/merge-jobs.yml @@ -12,6 +12,10 @@ permissions: jobs: test: runs-on: ubuntu-latest + permissions: + contents: read + # The JUnit report publishes a check run. + checks: write steps: - name: Checkout From 77a769b9d42d31f3555c5c0c939c6e01bc6fe402 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:26:04 +0000 Subject: [PATCH 7/8] feat(http): Let server freshness headers extend past ttlMs by default 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> --- packages/cli/src/lib/response-cache.ts | 5 ++- packages/http/README.md | 15 ++++++--- packages/http/src/policy.test.ts | 31 ++++++++++--------- packages/http/src/policy.ts | 43 ++++++++++++++------------ 4 files changed, 51 insertions(+), 43 deletions(-) diff --git a/packages/cli/src/lib/response-cache.ts b/packages/cli/src/lib/response-cache.ts index 982ae37659..c7c2efe13f 100644 --- a/packages/cli/src/lib/response-cache.ts +++ b/packages/cli/src/lib/response-cache.ts @@ -45,11 +45,10 @@ const log = logger.withTag("response-cache"); /** * Freshness for a Sentry API URL: its fallback tier's TTL when the server - * sends no cache headers. The server's `max-age` may give more, since Sentry - * sets it only on endpoints whose data rarely changes. + * sends no cache headers. The server's `max-age` wins when it sends one. */ function freshness(url: string): FreshnessOptions { - return { ttlMs: FALLBACK_TTL_MS[classifyUrl(url)], maxTtlMs: Infinity }; + return { ttlMs: FALLBACK_TTL_MS[classifyUrl(url)] }; } /** diff --git a/packages/http/README.md b/packages/http/README.md index 5a30cea31b..bfe5ed52ec 100644 --- a/packages/http/README.md +++ b/packages/http/README.md @@ -38,12 +38,17 @@ const response = await fetchWithCache({ ### Freshness -- `ttlMs` is how long a response serves without a request. `0` revalidates - every read. - Server freshness headers (`Cache-Control: max-age` or `no-cache`, and - `Expires`) can only shorten `ttlMs`, never extend it, so a server `max-age` cannot make a read skip revalidation - longer than you allow. Set `maxTtlMs` to let the server's headers give more, - such as `Infinity` to follow them. + `Expires`) decide how long a response serves without a request, 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 of those headers. `0` + revalidates every such read. +- `maxTtlMs` is an optional hard ceiling, for callers that learn of changes + another way. Junior's GitHub reads, for example, rely on webhook + invalidation: they pass `ttlMs: 0` and `maxTtlMs: 0`, so a server `max-age` + never skips the revalidation that picks up a change. - A stale entry with a validator stays in the store for `retainMs` (24 hours by default) so it can be revalidated. - With `staleIfError`, a stale entry also stays without a validator. When `send` diff --git a/packages/http/src/policy.test.ts b/packages/http/src/policy.test.ts index 0b2c46ad3b..9cdc287e13 100644 --- a/packages/http/src/policy.test.ts +++ b/packages/http/src/policy.test.ts @@ -236,13 +236,13 @@ describe("storeResponse", () => { expect(cache.ttls).toEqual([TTL + MINUTE]); }); - it("caps the server's max-age at the caller's TTL unless maxTtlMs raises it", async () => { + it("keeps an entry for the server's max-age unless maxTtlMs caps it", async () => { const cache = recordingStore(); const longLivedResponse = () => json(BODY, { "cache-control": "private, max-age=3600" }); await store(cache, longLivedResponse()); - await store(cache, longLivedResponse(), { maxTtlMs: Infinity }); - expect(cache.ttls).toEqual([TTL, 3_600_000]); + await store(cache, longLivedResponse(), { maxTtlMs: TTL }); + expect(cache.ttls).toEqual([3_600_000, TTL]); }); }); @@ -268,19 +268,9 @@ describe("lookupResponse freshness", () => { expect((await lookup(cache, { ttlMs: 0 }))?.kind).toBe("stale"); }); - it("does not let server max-age outlast the caller's TTL", async () => { + it("lets server max-age outlast the caller's TTL", async () => { const cache = createMemoryStore(); - const response = json(BODY, { - "cache-control": "private, max-age=600", - etag: '"v1"', - }); - await store(cache, response, { ttlMs: 0 }); - expect((await lookup(cache, { ttlMs: 0 }))?.kind).toBe("stale"); - }); - - it("lets server max-age outlast the TTL with maxTtlMs", async () => { - const cache = createMemoryStore(); - const freshness = { ttlMs: MINUTE, maxTtlMs: Infinity }; + const freshness = { ttlMs: MINUTE }; await store( cache, json(BODY, { "cache-control": "private, max-age=600" }), @@ -290,6 +280,17 @@ describe("lookupResponse freshness", () => { expect((await lookup(cache, freshness))?.kind).toBe("hit"); }); + it("revalidates every read despite server max-age with maxTtlMs: 0", async () => { + const cache = createMemoryStore(); + const freshness = { ttlMs: 0, maxTtlMs: 0 }; + const response = json(BODY, { + "cache-control": "private, max-age=600", + etag: '"v1"', + }); + await store(cache, response, freshness); + expect((await lookup(cache, freshness))?.kind).toBe("stale"); + }); + it("lets server max-age shorten the caller's TTL", async () => { const cache = createMemoryStore(); await store( diff --git a/packages/http/src/policy.ts b/packages/http/src/policy.ts index aaf3ab3737..48c5f6bce8 100644 --- a/packages/http/src/policy.ts +++ b/packages/http/src/policy.ts @@ -1,8 +1,8 @@ /** * HTTP caching decisions for GET responses, through `http-cache-semantics` - * (RFC 9111). The caller's `ttlMs` is how long a response stays fresh, and - * server cache directives can only shorten it, unless the caller raises - * `maxTtlMs`. A stale entry with an `ETag` or `Last-Modified` is kept for a + * (RFC 9111). Server freshness headers set how long a response stays fresh, + * up to the caller's optional `maxTtlMs`; the caller's `ttlMs` applies when + * the server sends none. A stale entry with an `ETag` or `Last-Modified` is kept for a * retention window and renewed by a matching 304; with `staleIfError`, a * stale entry is also kept to serve when the server fails. * @@ -46,16 +46,17 @@ const encoder = new TextEncoder(); */ export type FreshnessOptions = { /** - * How long a response serves without asking the server. `0` revalidates - * every read. Server cache directives (`max-age`, `no-cache`, `Expires`) - * can shorten it. + * How long a response serves without asking the server when the server + * sends no freshness headers (`max-age`, `no-cache`, `Expires`). `0` + * revalidates every such read. When the server sends them, they decide, + * longer or shorter. */ ttlMs: number; /** - * The longest freshness that server directives may give. Defaults to - * `ttlMs`, so a server `max-age` never makes a read skip revalidation for - * longer than the caller allows. Pass `Infinity` to let the server's - * directives win. + * A hard ceiling on freshness, whatever the server says. Unset by + * default, so the server's headers win. Set it when the caller learns of + * changes another way: `0` with webhook invalidation, for example, keeps + * a server `max-age` from skipping revalidation. */ maxTtlMs?: number; /** @@ -221,9 +222,9 @@ function varyMatches(policy: CachePolicy, request: GetRequest): boolean { } /** - * Whether `entry` can be served without revalidation: within the caller's - * TTL, and, when the server sent directives, within theirs too (capped at - * `maxTtlMs`). + * Whether `entry` can be served without revalidation: within the server's + * freshness lifetime when it sent one, otherwise within the caller's TTL, + * and never past `maxTtlMs`. */ function isEntryFresh( policy: CachePolicy, @@ -232,11 +233,12 @@ function isEntryFresh( options: FreshnessOptions, ): boolean { const ageMs = Date.now() - entry.createdAt; - if (!hasServerCacheDirectives(policy)) { - return ageMs < options.ttlMs; + if (ageMs >= (options.maxTtlMs ?? Infinity)) { + return false; } - const maxTtlMs = options.maxTtlMs ?? options.ttlMs; - return ageMs < maxTtlMs && policy.satisfiesWithoutRevalidation(request); + return hasServerCacheDirectives(policy) + ? policy.satisfiesWithoutRevalidation(request) + : ageMs < options.ttlMs; } /** @@ -245,9 +247,10 @@ function isEntryFresh( * entries for errors. */ function retentionMs(policy: CachePolicy, options: FreshnessOptions): number { - const freshMs = hasServerCacheDirectives(policy) - ? Math.min(policy.timeToLive(), options.maxTtlMs ?? options.ttlMs) - : options.ttlMs; + const freshMs = Math.min( + hasServerCacheDirectives(policy) ? policy.timeToLive() : options.ttlMs, + options.maxTtlMs ?? Infinity, + ); return hasValidator(policy) || options.staleIfError ? freshMs + (options.retainMs ?? REVALIDATION_WINDOW_MS) : freshMs; From a2f427eebf861c8269f3d349afffa5910cd20e48 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:26:17 +0000 Subject: [PATCH 8/8] ci: Test release branches in test.yml and keep the release choice - `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. --- .craft.yml | 3 +- .github/workflows/merge-jobs.yml | 57 +++++-------------------------- .github/workflows/release.yml | 11 ++++-- .github/workflows/test.yml | 3 +- docs/operations/github-actions.md | 22 +++++++----- scripts/workflow-policy.test.mjs | 35 +++++++++++++++++++ 6 files changed, 69 insertions(+), 62 deletions(-) diff --git a/.craft.yml b/.craft.yml index 60f1aa4b2e..bb8a6f71fe 100644 --- a/.craft.yml +++ b/.craft.yml @@ -136,7 +136,8 @@ workspaces: # Standalone npm libraries. Each is released on its own, with # `@` tags and `release//` branches, and # `merge-jobs.yml` packs every one of them. To publish another package - # from `packages/`, add its directory name here. No preReleaseCommand: + # from `packages/`, add its directory name here and to release.yml's + # `product` options. No preReleaseCommand: # Craft bumps package.json through the npm target. packages/{http,logger}: changelog: diff --git a/.github/workflows/merge-jobs.yml b/.github/workflows/merge-jobs.yml index 866b23a514..e897f6fbc5 100644 --- a/.github/workflows/merge-jobs.yml +++ b/.github/workflows/merge-jobs.yml @@ -2,54 +2,13 @@ name: Post-merge tasks on: push: - # The CLI's release branches are built by cli-build.yml. - branches: ["main", "release/**", "!release/cli/**"] + branches: ["main", "release/**"] workflow_dispatch: permissions: contents: read jobs: - test: - runs-on: ubuntu-latest - permissions: - contents: read - # The JUnit report publishes a check run. - checks: write - - steps: - - name: Checkout - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - with: - persist-credentials: false - - - name: Setup pnpm - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - - - name: Set up Node - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version-file: "package.json" - - - name: Install dependencies - run: pnpm install - - - name: Build - run: pnpm --filter '@sentry/mcp-core...' --filter @sentry/logger --if-present run build - - - name: Run linter - run: pnpm lint - - - name: Run tests - run: pnpm test:ci - - - name: Publish Test Report - uses: mikepenz/action-junit-report@cf701569b05ccdd861a76b8607a66d76f6fd4857 - if: ${{ !cancelled() }} - with: - report_paths: "**/*.junit.xml" - comment: false - # Every Craft workspace without its own artifact provider is an npm # library whose tarball this workflow builds. discover-packages: @@ -59,12 +18,12 @@ jobs: steps: - name: Checkout - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + uses: actions/checkout@v4 with: persist-credentials: false - name: Set up Node - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + uses: actions/setup-node@v4 with: node-version-file: "package.json" @@ -85,7 +44,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + uses: actions/checkout@v4 with: persist-credentials: false @@ -93,7 +52,7 @@ jobs: uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - name: Set up Node - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + uses: actions/setup-node@v4 with: node-version-file: "package.json" @@ -110,7 +69,7 @@ jobs: run: pnpm pack --pack-destination dist - name: Upload tarball - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + uses: actions/upload-artifact@v4 with: name: npm-${{ matrix.name }} path: ${{ matrix.workspace }}/dist/*.tgz @@ -118,12 +77,12 @@ jobs: # Craft reads every tarball from one artifact named after the commit. archive: - needs: [test, package] + needs: package runs-on: ubuntu-latest steps: - name: Archive artifacts - uses: actions/upload-artifact/merge@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + uses: actions/upload-artifact/merge@v4 with: name: ${{ github.sha }} pattern: npm-* diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 651dece236..2a50f995ff 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,10 +4,16 @@ on: workflow_dispatch: inputs: product: - description: "Package to release: a directory under packages/ with a .craft.yml workspace, such as cli, http, or logger" + description: Package to release, by its directory under packages/ required: true - type: string + type: choice default: cli + # One per .craft.yml workspace; scripts/workflow-policy.test.mjs + # checks that they match. + options: + - cli + - http + - logger bump: description: "Version bump: auto (from commits), pre (next prerelease), or an explicit bump type" required: true @@ -63,7 +69,6 @@ jobs: env: GITHUB_TOKEN: ${{ steps.token.outputs.token }} with: - # Craft fails, listing the workspaces it has, for any other name. # The `cli` release also publishes @sentry/mcp-server at the same # version. workspace: packages/${{ inputs.product }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 17370816d7..d56b8176c2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,7 +2,8 @@ name: Test on: push: - branches: [main] + # Release branches too, so Craft finds the checks on a release commit. + branches: [main, "release/**"] pull_request: merge_group: diff --git a/docs/operations/github-actions.md b/docs/operations/github-actions.md index 6706f2499f..59f832724f 100644 --- a/docs/operations/github-actions.md +++ b/docs/operations/github-actions.md @@ -11,7 +11,8 @@ and docs when `SENTRY_CLIENT_ID` is available. ### test.yml -Runs on pushes to `main`, pull requests, and merge queue entries. Discovery +Runs on pushes to `main` and release branches, pull requests, and merge queue +entries. Discovery reads pnpm workspace projects and their package scripts. Pull requests check changed projects, their workspace consumers, and semantic dependencies (the CLI docs depend on `sentry`). Root-level changes and non-PR events check every @@ -156,19 +157,24 @@ token pushes the branch and opens the PR, so `test.yml` runs on it. ### release.yml and merge-jobs.yml -`release.yml` prepares a release of one package with Craft. Its `product` input -is a directory under `packages/`, such as `cli`, `http`, or `logger`, and Craft -fails for a directory that has no `.craft.yml` workspace. +`release.yml` prepares a release of one package with Craft. Its `product` +choice is a directory under `packages/`, such as `cli`, `http`, or `logger`. +GitHub cannot fill a choice from `.craft.yml`, so +`scripts/workflow-policy.test.mjs` fails when the options and the `packages/` +workspaces in `.craft.yml` differ. -`merge-jobs.yml` runs on `main` and on every release branch except the CLI's. -It lists the Craft workspaces that use the default artifact provider with +`merge-jobs.yml` runs on `main` and on every release branch. It lists the +Craft workspaces that use the default artifact provider with `scripts/npm-library-workspaces.mjs`, packs each one in a parallel matrix job, and merges the tarballs into the artifact named after the commit, where Craft -reads them. The CLI sets its own artifact provider and is built by +reads them. `test.yml` runs the tests on the same commits. The CLI sets its own +artifact provider: it ships platform binaries, a Homebrew formula, the docs +site, and `@sentry/mcp-server` along with its npm package, all built by `cli-build.yml`. To publish another package from `packages/`, add its directory name to the -`packages/{...}` workspace key in `.craft.yml`. Neither workflow needs a change. +`packages/{...}` workspace key in `.craft.yml` and to `release.yml`'s +`product` options. ## Package CI checks diff --git a/scripts/workflow-policy.test.mjs b/scripts/workflow-policy.test.mjs index 770395ddee..ae3f786a2f 100644 --- a/scripts/workflow-policy.test.mjs +++ b/scripts/workflow-policy.test.mjs @@ -30,6 +30,29 @@ const PULL_REQUEST_EVENTS = [ ]; const workflowsDirectory = new URL("../.github/workflows/", import.meta.url); +const craftConfig = new URL("../.craft.yml", import.meta.url); + +/** + * Directory names under `packages/` that `.craft.yml` releases. Expands a + * `packages/{a,b}` key; other globs would need Craft to resolve them. + */ +function craftPackageNames(source) { + return [...source.matchAll(/^ {2}packages\/([^:\s]+):\s*$/gm)] + .flatMap(([, key]) => + key.startsWith("{") && key.endsWith("}") + ? key.slice(1, -1).split(",") + : [key], + ) + .toSorted((a, b) => a.localeCompare(b)); +} + +/** Return the options of release.yml's `product` choice input. */ +function releaseProductOptions(source) { + const block = /^ {6}product:\n((?: {8}.*\n)+)/m.exec(source)?.[1] ?? ""; + return [...block.matchAll(/^ {10}- (\S+)$/gm)] + .map(([, name]) => name) + .toSorted((a, b) => a.localeCompare(b)); +} /** Return the text of a workflow's top-level `on` trigger. */ function workflowTriggers(source) { @@ -99,4 +122,16 @@ describe("workflow policy", () => { ); } }); + + it("offers one release.yml product per .craft.yml package", () => { + const products = releaseProductOptions( + readFileSync(new URL("release.yml", workflowsDirectory), "utf8"), + ); + assert.ok(products.length > 0, "release.yml has no product options"); + assert.deepEqual( + products, + craftPackageNames(readFileSync(craftConfig, "utf8")), + "release.yml's product options must match the packages/ workspaces in .craft.yml.", + ); + }); });