Skip to content

feat(cache): centralize mutation invalidation at the HTTP layer (#792)#801

Open
BYK wants to merge 2 commits intomainfrom
cli-ux-centralize-cache-invalidation
Open

feat(cache): centralize mutation invalidation at the HTTP layer (#792)#801
BYK wants to merge 2 commits intomainfrom
cli-ux-centralize-cache-invalidation

Conversation

@BYK
Copy link
Copy Markdown
Member

@BYK BYK commented Apr 21, 2026

Closes #792. Follow-up to #788.

Summary

The per-site invalidate* helpers in api/issues.ts, api/projects.ts, and api/dashboards.ts are replaced by a single post-mutation hook in authenticatedFetch that auto-invalidates the cache for every successful non-GET. Prefix computation lives in a new src/lib/cache-keys.ts module.

Layer 1: HTTP-layer hook (new)

invalidateAfterMutation fires after fetchWithRetry returns a 2xx non-GET response:

  • Hierarchy walk — for /api/0/organizations/{org}/releases/1.0.0/deploys/, sweeps the URL path plus every ancestor down to the owner level (releases/1.0.0/, releases/, organizations/{org}/). The bare top-level organizations/ root is deliberately not swept — sweeping it on every mutation would evict unrelated cross-org caches.
  • Cross-endpoint rules — tiny table for the 2 cases where a mutation affects a different URL tree:
    • POST /api/0/teams/{org}/{team}/projects/ invalidates /api/0/organizations/{org}/projects/
    • DELETE /api/0/projects/{org}/{project}/ invalidates /api/0/organizations/{org}/projects/

The hook is awaited before returning the response, so a subsequent read in the same command sees fresh data. Identity-gated via the existing sweep primitive (no cross-account eviction). classifyUrl === "no-cache" paths (autofix / root-cause) are never cached to begin with, so sweeping them is a no-op.

Layer 2: Command-level override (deferred)

Issue #792 proposed an optional invalidates callback on buildCommand for cross-endpoint fan-outs the HTTP layer can't know about. Turned out the 2 hardcoded rules above cover every current case — deferred the callback API to when a real use case emerges.

Coverage

Every mutation in src/lib/api/ is now covered for free, including ones that had no invalidation before:

  • release create/update/delete, release deploy, set-commits*
  • team create, member add
  • dashboard create
  • trial start

sentry api -X POST/PUT/DELETE ... also gets auto-invalidation — users of the raw escape hatch no longer need --fresh on follow-up reads.

Removed

  • api/issues.ts: invalidateIssueCaches, invalidateIssueDetailCaches, invalidateOrgIssueList + their call sites in updateIssueStatus / mergeIssues.
  • api/projects.ts: invalidateProjectCaches, invalidateOrgProjectCache + call sites in createProject / deleteProject.
  • api/dashboards.ts: inline invalidateCachedResponse in updateDashboard.

Net: -156 lines of source, +130 lines for cache-keys.ts.

Tests

  • test/lib/cache-keys.test.ts (14 tests) — hierarchy walk (with the owner-level cap), cross-endpoint rules, query-string stripping, unparseable URLs, self-hosted bases, dedup.
  • test/lib/sentry-client.invalidation.test.ts (5 integration tests) — successful mutation clears self + list, failed mutation leaves cache alone, GET doesn't invalidate, cross-endpoint rule fires, identity isolation holds.

Full unit suite: 5546 passing. bun run typecheck, bun run lint clean.

Follow-ups

One minor optimization deferred: when the hook computes multiple prefixes, Promise.all kicks off independent invalidateCachedResponsesMatching calls, each doing its own readdir + per-file parse. For typical cache sizes (few hundred entries) this is negligible, but the natural shape is "read the dir once, match every entry against ALL prefixes, unlink if any match." A future invalidateCachedResponsesMatchingAny(prefixes: string[]) API would eliminate the redundant I/O. Not done here to keep the PR scoped.

Follow-up to #788. The per-site `invalidate*` helpers in
`api/issues.ts`, `api/projects.ts`, and `api/dashboards.ts` are
replaced by a single post-mutation hook in `authenticatedFetch` that
auto-invalidates the cache for every successful non-GET.

## Layer 1: HTTP hook (new)

`invalidateAfterMutation` fires in `sentry-client.ts` after
`fetchWithRetry` returns a 2xx non-GET response. Prefix computation
is delegated to a new `src/lib/cache-keys.ts` module:

- **Hierarchy walk.** For a mutation on
  `/api/0/organizations/{org}/releases/1.0.0/deploys/`, sweep the
  URL path plus every ancestor: `releases/1.0.0/`, `releases/`,
  `organizations/{org}/`, `organizations/`. Catches the
  corresponding GET caches in a single pass.
- **Cross-endpoint rules.** Tiny table for the 2 cases where a
  mutation affects a different URL tree:
    - `POST /teams/{org}/{team}/projects/` invalidates
      `/organizations/{org}/projects/`
    - `DELETE /projects/{org}/{project}/` invalidates
      `/organizations/{org}/projects/`

The hook is awaited so a subsequent read in the same command sees
fresh data. Identity-gated via the existing sweep primitive, so a
mutation by one account can't evict another account's cache.
`classifyUrl === "no-cache"` paths (autofix/root-cause) skip
naturally because reads to those URLs aren't cached either.

## Layer 2: Command-level override (deferred)

Issue #792 proposed an optional `invalidates` callback on
`buildCommand` for cross-endpoint fan-outs. Turned out the 2
hardcoded rules above cover every current case; deferring the
callback API to when a use case actually emerges.

## Coverage

Every mutation in `src/lib/api/` is now covered for free, including
mutations that had no invalidation before (`releases`, `teams`,
`dashboards` create, `trials`). `sentry api -X POST/PUT/DELETE ...`
also gets auto-invalidation — users of the raw escape hatch no
longer need `--fresh` on follow-up reads.

## Removed

- `api/issues.ts`: `invalidateIssueCaches`,
  `invalidateIssueDetailCaches`, `invalidateOrgIssueList` plus
  their call sites in `updateIssueStatus` and `mergeIssues`.
- `api/projects.ts`: `invalidateProjectCaches`,
  `invalidateOrgProjectCache` plus call sites in `createProject`
  and `deleteProject`.
- `api/dashboards.ts`: inline `invalidateCachedResponse` in
  `updateDashboard`.

Net: -156 lines source + new `cache-keys.ts` (~130 lines).

## Tests

- `test/lib/cache-keys.test.ts` — 13 tests covering the hierarchy
  walk, cross-endpoint rules, query-string stripping, unparseable
  URLs, self-hosted bases, and dedup.
- `test/lib/sentry-client.invalidation.test.ts` — 5 integration
  tests: successful mutation clears self + list, failed mutation
  leaves cache alone, GET doesn't invalidate, cross-endpoint rule
  fires, identity isolation holds.

Full unit suite: 5545 passing.

Closes #792.
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 21, 2026

Semver Impact of This PR

🟡 Minor (new features)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


New Features ✨

Cache

Other

Bug Fixes 🐛

Init

  • Send dirListing/fileCache/existingSentry via initialState by betegon in #796
  • Force process exit after wizard completes by betegon in #782

Other

Documentation 📚

  • Fix auth token precedence, update stale architecture tree, and documentation audit report by cursor in #783

Internal Changes 🔧

  • (init) Trim deprecated --features help entries by MathurAditya724 in #781
  • (issue) Skip redundant API lookups via project+issue-org caches by BYK in #794
  • Regenerate docs by github-actions[bot] in 58a84035

🤖 This preview updates automatically when you update the PR.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 21, 2026

PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://cli.sentry.dev/_preview/pr-801/

Built to branch gh-pages at 2026-04-21 13:26 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 21, 2026

Codecov Results 📊

138 passed | Total: 138 | Pass Rate: 100% | Execution Time: 0ms

📊 Comparison with Base Branch

Metric Change
Total Tests
Passed Tests
Failed Tests
Skipped Tests

✨ No test changes detected

All tests are passing successfully.

✅ Patch coverage is 98.53%. Project has 1721 uncovered lines.
✅ Project coverage is 95.72%. Comparing base (base) to head (head).

Files with missing lines (1)
File Patch % Lines
src/lib/cache-keys.ts 97.96% ⚠️ 1 Missing
Coverage diff
@@            Coverage Diff             @@
##          main       #PR       +/-##
==========================================
+ Coverage    95.64%    95.72%    +0.08%
==========================================
  Files          280       281        +1
  Lines        40248     40232       -16
  Branches         0         0         —
==========================================
+ Hits         38494     38511       +17
- Misses        1754      1721       -33
- Partials         0         0         —

Generated by Codecov Action

Copy link
Copy Markdown
Contributor

@cursor cursor Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit d51ba3a. Configure here.

Comment thread src/lib/cache-keys.ts
…atch

Two review-feedback fixes on #801:

1. **Cap the hierarchy walk.** Before: every mutation swept the bare
   top-level prefix (`/api/0/organizations/`, `/api/0/teams/`, etc.),
   which would evict cross-org caches on any single-org mutation.
   Now the walk stops at 2 segments — owner level
   (`organizations/{org}/`). Paths that are already ≤ 2 segments
   still walk to their root (a mutation targeting the root itself
   should clear its cache). Added a new test for the two-segment case.

2. **Drop the defensive try/catch in `invalidateAfterMutation`.**
   `invalidateCachedResponsesMatching` is already contractually
   no-throw; wrapping its `Promise.all` in another try/catch was
   dead code. Matches BYK's brevity preference in the lore.

No behavior change beyond the walk cap. Tests updated accordingly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Centralize mutation cache invalidation via a command-level helper

1 participant