Skip to content

Cache#740

Merged
feruzm merged 9 commits into
developfrom
improve
Apr 6, 2026
Merged

Cache#740
feruzm merged 9 commits into
developfrom
improve

Conversation

@feruzm
Copy link
Copy Markdown
Member

@feruzm feruzm commented Apr 5, 2026

Summary by CodeRabbit

  • New Features

    • Tiered HTML caching with age-aware entry refinement and Cache-Control headers
    • Cloudflare cache purge script for manual content invalidation
    • Enhanced event-loop monitoring with stall detection and recovery alerts
  • Bug Fixes

    • Added request timeouts (10s) across internal APIs and Mattermost integrations
  • Chores

    • Removed legacy Intl/browser polyfills and two static pages (Guest Posts, Contribute)
    • Optimized concurrent RPC calls for account data

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 5, 2026

Caution

Review failed

Pull request was closed or merged during review

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2929362d-133c-4dfe-a00d-e68f7395891a

📥 Commits

Reviewing files that changed from the base of the PR and between 1929cd4 and 3d671c2.

⛔ Files ignored due to path filters (7)
  • packages/sdk/dist/browser/index.d.ts is excluded by !**/dist/**
  • packages/sdk/dist/browser/index.js is excluded by !**/dist/**
  • packages/sdk/dist/browser/index.js.map is excluded by !**/dist/**, !**/*.map
  • packages/sdk/dist/node/index.cjs is excluded by !**/dist/**
  • packages/sdk/dist/node/index.cjs.map is excluded by !**/dist/**, !**/*.map
  • packages/sdk/dist/node/index.mjs is excluded by !**/dist/**
  • packages/sdk/dist/node/index.mjs.map is excluded by !**/dist/**, !**/*.map
📒 Files selected for processing (4)
  • packages/sdk/CHANGELOG.md
  • packages/sdk/package.json
  • packages/wallets/CHANGELOG.md
  • packages/wallets/package.json
✅ Files skipped from review due to trivial changes (4)
  • packages/sdk/CHANGELOG.md
  • packages/sdk/package.json
  • packages/wallets/CHANGELOG.md
  • packages/wallets/package.json

📝 Walkthrough

Walkthrough

Removes two static pages and related polyfills/deps; adds Next.js middleware cache policy, entry-age post caching and refinement, event-loop watchdog and sanitization, request timeouts, SDK/search tweaks, tests, and a Cloudflare purge script.

Changes

Cohort / File(s) Summary
Removed Static Pages & Styles
apps/web/src/app/(staticPages)/guest-post/page.tsx, apps/web/src/app/contribute/page.tsx, apps/web/src/styles/static-pages.scss, apps/web/src/routes.ts
Deleted guest-posts and contribute page implementations, removed their route keys and corresponding SCSS selectors.
Dependency / Polyfills
apps/web/package.json, apps/web/src/polyfills.ts
Removed intl dependency and associated Intl/Array polyfills; minor whitespace change in BigInt warning.
Middleware Cache Policy
apps/web/src/features/next-middleware/cache-policy.ts, apps/web/src/features/next-middleware/post-age-cache.ts, apps/web/src/features/next-middleware/index.ts
Added deterministic cache-tier resolver, entry URL parsing and entry-age tiering, in-memory post-age cache with deduped refreshes, and re-exports.
Middleware Integration
apps/web/src/middleware.ts
Middleware now wraps responses, rejects write methods (405), applies Cache-Control and x-cache-tier, refines entry-tier for anonymous users via post-age cache and schedules background refresh with event.waitUntil.
Event Loop Monitor
apps/web/src/event-loop-monitor.ts, apps/web/src/specs/utils/event-loop-monitor.spec.ts
Added sanitizeUrl export and tests, synchronous stderr logging, per-request IDs, worker-thread watchdog with heartbeat and configurable stuck threshold.
Request Timeouts / Mattermost
apps/web/src/server/mattermost.ts, packages/sdk/src/modules/search/..., packages/sdk/src/modules/search/requests.ts, packages/sdk/src/modules/core/config.ts
Added INTERNAL_API_TIMEOUT_MS (10s); applied AbortSignal.timeout to various fetches; Mattermost fetch uses timeout signal and maps timeouts to 504 MattermostError.
Query & RPC Optimizations
apps/web/src/core/react-query/index.ts, packages/sdk/src/modules/accounts/queries/get-account-full-query-options.ts
Disabled React Query retries on server; combined two RPCs into concurrent Promise.all with inline error handling for account full query.
Tests & Tools
apps/web/src/specs/features/next-middleware/cache-policy.spec.ts, apps/web/src/specs/features/next-middleware/post-age-cache.spec.ts, apps/web/src/specs/utils/event-loop-monitor.spec.ts, scripts/purge-cache.sh
Added comprehensive Vitest suites for cache policy, post-age cache, and sanitizeUrl; added Cloudflare purge script with batching and strict error handling.
SDK Versioning / Changelog
packages/sdk/CHANGELOG.md, packages/sdk/package.json, packages/wallets/CHANGELOG.md, packages/wallets/package.json
Bumped packages/sdk 2.1.0→2.1.1 and packages/wallets 3.0.0→3.0.1; added changelog entries.
Search Fetch Updates
packages/sdk/src/modules/search/queries/*, packages/sdk/src/modules/search/requests.ts
Applied request timeouts via AbortSignal.timeout(INTERNAL_API_TIMEOUT_MS) to several search-related fetches.

Sequence Diagram(s)

sequenceDiagram
    participant Client as "Client"
    participant Middleware as "Next Middleware"
    participant CachePolicy as "Cache Policy\nResolver"
    participant PostAgeCache as "Post-Age\nCache"
    participant HiveRPC as "Hive RPC"
    participant Response as "Response"

    Client->>Middleware: GET /category/@author/permlink
    Middleware->>CachePolicy: getCachePolicyForPath(path)
    CachePolicy-->>Middleware: { tier: "entry", ... }

    alt Unauthenticated & entry tier
        Middleware->>Middleware: parseEntryUrl(path)
        Middleware->>PostAgeCache: getCachedPostCreatedMs(author, permlink)
        alt Cached timestamp
            PostAgeCache-->>Middleware: timestamp(ms)
            Middleware->>CachePolicy: getEntryTierForAge(ageMs)
            CachePolicy-->>Middleware: refined tier
        else Cache miss (undefined)
            PostAgeCache-->>Middleware: undefined
            Middleware->>HiveRPC: refreshPostCreatedMs(...)  (via event.waitUntil)
            HiveRPC-->>PostAgeCache: created timestamp -> cache
        else Negative cache (null)
            PostAgeCache-->>Middleware: null
        end
    end

    Middleware->>Middleware: buildCacheControlHeader(policy, isLoggedIn)
    Middleware->>Response: set Cache-Control + x-cache-tier
    Response-->>Client: Response with cache directives
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

"I'm a rabbit in the codebase glade,
I pruned old pages and made new shade;
Watchdogs hum and cache tiers sing,
Timeouts set — oh what a spring! 🐇"

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Cache' is vague and generic, providing minimal information about the actual changes made in the PR. Use a more descriptive title that summarizes the main objective, such as 'Implement HTML cache policy and post age caching for middleware' or 'Add cache headers and edge-isolate post age tracking'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch improve

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (2)
apps/web/src/middleware.ts (2)

35-42: ⚠️ Potential issue | 🟠 Major

Header-based Server Action bypass is too broad.

next-action is just a client-supplied header, so any POST/PATCH to a page route can use it to skip the 405 fast-path and re-enter the expensive Next.js pipeline this guard is meant to avoid. If Server Actions need an exception later, it should be scoped to actual action endpoints, not raw header presence.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/src/middleware.ts` around lines 35 - 42, The middleware currently
treats any request with the next-action header as a legitimate Server Action
(isServerAction), allowing client-supplied headers to bypass the 405 fast-path;
change this to only accept Server Actions for known action endpoints by
replacing the header-only check with a route-scoped validation (e.g., add a
helper isServerActionRoute(pathname) or match a specific action route pattern)
and only treat the request as a server action if both the pathname matches that
action route and, optionally, the header/value validation passes; update the
isServerAction usage in the write-method guard (where isWriteMethod, isApiRoute,
isPlausibleProxy, isServerAction are checked) to use this stricter
isServerActionRoute check instead of request.headers.has("next-action").

91-92: ⚠️ Potential issue | 🟠 Major

Public cache headers are still set before the real status exists.

NextResponse.next() is only a passthrough 200 here, so applyCacheHeaders() derives a public Cache-Control purely from the pathname. Dynamic entry/profile routes that later resolve to 404/500/redirects will keep that header, which can make misses and transient failures sticky in shared cache.

Also applies to: 128-129

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/src/middleware.ts` around lines 91 - 92, The middleware is applying
public cache headers immediately after calling NextResponse.next(), which is a
passthrough 200 and can cause incorrect public caching for routes that later
resolve to 404/500/redirect; stop setting cache headers for the
NextResponse.next() passthrough. Change the code so applyCacheHeaders(request,
response, path, event) is only invoked for responses the middleware actively
constructs (e.g., branches that return NextResponse.rewrite(),
NextResponse.redirect(), or any response with a final status), and remove or
guard the applyCacheHeaders call for the NextResponse.next() path (use the
response type/branch checks around NextResponse.rewrite/redirect or only call
applyCacheHeaders after you have a non-passthrough/final response).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@apps/web/src/middleware.ts`:
- Around line 35-42: The middleware currently treats any request with the
next-action header as a legitimate Server Action (isServerAction), allowing
client-supplied headers to bypass the 405 fast-path; change this to only accept
Server Actions for known action endpoints by replacing the header-only check
with a route-scoped validation (e.g., add a helper isServerActionRoute(pathname)
or match a specific action route pattern) and only treat the request as a server
action if both the pathname matches that action route and, optionally, the
header/value validation passes; update the isServerAction usage in the
write-method guard (where isWriteMethod, isApiRoute, isPlausibleProxy,
isServerAction are checked) to use this stricter isServerActionRoute check
instead of request.headers.has("next-action").
- Around line 91-92: The middleware is applying public cache headers immediately
after calling NextResponse.next(), which is a passthrough 200 and can cause
incorrect public caching for routes that later resolve to 404/500/redirect; stop
setting cache headers for the NextResponse.next() passthrough. Change the code
so applyCacheHeaders(request, response, path, event) is only invoked for
responses the middleware actively constructs (e.g., branches that return
NextResponse.rewrite(), NextResponse.redirect(), or any response with a final
status), and remove or guard the applyCacheHeaders call for the
NextResponse.next() path (use the response type/branch checks around
NextResponse.rewrite/redirect or only call applyCacheHeaders after you have a
non-passthrough/final response).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 71dbdfbc-c71e-4822-a864-f7c0007cefa7

📥 Commits

Reviewing files that changed from the base of the PR and between 60d0289 and 1929cd4.

📒 Files selected for processing (6)
  • apps/web/src/middleware.ts
  • packages/sdk/src/modules/core/config.ts
  • packages/sdk/src/modules/search/queries/get-search-api-infinite-query-options.ts
  • packages/sdk/src/modules/search/queries/get-search-query-options.ts
  • packages/sdk/src/modules/search/queries/get-similar-entries-query-options.ts
  • packages/sdk/src/modules/search/requests.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/sdk/src/modules/core/config.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/sdk/src/modules/search/queries/get-search-api-infinite-query-options.ts
  • packages/sdk/src/modules/search/queries/get-similar-entries-query-options.ts
  • packages/sdk/src/modules/search/requests.ts
  • packages/sdk/src/modules/search/queries/get-search-query-options.ts

@feruzm feruzm added the patch Bug fixes and patches (1.0.0 → 1.0.1), add this only if any packages/ have patch changes in PR label Apr 6, 2026
@feruzm feruzm merged commit c067963 into develop Apr 6, 2026
1 check was pending
@feruzm feruzm deleted the improve branch April 6, 2026 17:05
@coderabbitai coderabbitai Bot mentioned this pull request Apr 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch Bug fixes and patches (1.0.0 → 1.0.1), add this only if any packages/ have patch changes in PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant