Skip to content

Add in-memory caching delegating handler to Boilerplate (#9897)#9900

Merged
msynk merged 20 commits intobitfoundation:developfrom
yasmoradi:9897
Feb 15, 2025
Merged

Add in-memory caching delegating handler to Boilerplate (#9897)#9900
msynk merged 20 commits intobitfoundation:developfrom
yasmoradi:9897

Conversation

@yasmoradi
Copy link
Member

@yasmoradi yasmoradi commented Feb 15, 2025

closes #9897

Summary by CodeRabbit

  • New Features

    • Introduced an advanced caching mechanism to optimize HTTP request handling and improve response performance.
  • Refactor

    • Reordered the HTTP processing pipeline to better integrate caching.
    • Updated caching terminology in response policies for clarity and consistency.
  • Chores

    • Adjusted service registrations and dependency configurations to align with the new caching approach.

@yasmoradi yasmoradi requested a review from msynk February 15, 2025 03:53
@coderabbitai
Copy link

coderabbitai bot commented Feb 15, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes modify both client and server projects with a focus on caching. On the client side, a new CacheDelegatingHandler and associated ResponseMemoryCacheItems have been added and registered via dependency injection, and the HTTP message handlers chain has been updated to include this new handler. On the server side, memory cache service registrations have been removed and caching terminology has been updated from “browserCache” to “clientCache” in the response policies. Additionally, the shared project now references the in-memory caching package and registers its services accordingly.

Changes

File(s) Change Summary
src/…/Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs, src/…/Client/Boilerplate.Client.Core/Services/HttpMessageHandlersChainFactory.cs, src/…/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/CacheDelegatingHandler.cs Added the registration for CacheDelegatingHandler in the service collection; introduced the new caching handler and ResponseMemoryCacheItems; updated the HTTP handler chain order to include caching logic.
src/…/Server/Boilerplate.Server.Api/Program.Services.cs, src/…/Server/Boilerplate.Server.Api/Services/AppResponseCachePolicy.cs, src/…/Server/Boilerplate.Server.Web/Program.Services.cs, src/…/Server/Boilerplate.Server.Web/Services/AppResponseCachePolicy.cs Removed memory cache service registrations; updated caching terminology (renamed browserCacheTtl to clientCacheTtl and adjusted comments); added a code generation directive in the API services.
src/…/Shared/Boilerplate.Shared.csproj, src/…/Shared/Extensions/ISharedServiceCollectionExtensions.cs Added a package reference for Microsoft.Extensions.Caching.Memory and registered memory caching in the shared service collection.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant CDH as CacheDelegatingHandler
    participant BH as Base Handler
    C->>CDH: Send HTTP Request
    alt Cache Hit
        CDH->>C: Return Cached Response
    else Cache Miss
        CDH->>BH: Forward Request
        BH->>CDH: Return New Response
        CDH->>C: Return Response (and cache it)
    end
Loading

Poem

I'm a rabbit happily on the run,
Hopping through changes under the coding sun.
Cache carrots now sprout in every chain,
Speeding requests like a joyful gain.
Cheers to new hops and fresh code terrain!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/CacheDelegatingHandler.cs (1)

65-73: Audit the size and content of cached response items.

Caching the entire response content, headers, and LogScopeData can be large or contain sensitive data. Confirm memory usage bounds and potential data leakage in multi-tenant scenarios. Also, consider making the class sealed if inheritance is not needed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94fcdd9 and 206c00a.

📒 Files selected for processing (9)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/CacheDelegatingHandler.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/HttpMessageHandlersChainFactory.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Program.Services.cs (0 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Services/AppResponseCachePolicy.cs (4 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Web/Program.Services.cs (0 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Web/Services/AppResponseCachePolicy.cs (4 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Boilerplate.Shared.csproj (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Extensions/ISharedServiceCollectionExtensions.cs (1 hunks)
💤 Files with no reviewable changes (2)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Program.Services.cs
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Web/Program.Services.cs
✅ Files skipped from review due to trivial changes (1)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/HttpMessageHandlersChainFactory.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (13)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/CacheDelegatingHandler.cs (3)

6-8: Constructor injection and handler chaining look good.

Using constructor injection to obtain IMemoryCache and chaining to another HttpMessageHandler is a clean approach. The internal access modifier is sensible if usage is strictly within this assembly.


9-19: Ensure that sensitive data isn’t stored in logs or cache.

The logScopeData dictionary and subsequent logScopeData usage may contain user-specific or private information. Verify that no personally identifiable or sensitive data is inadvertently cached and shared across requests.


41-63: Avoid caching non-GET or user-specific responses.

Currently, any successful request with a suitable CacheControl header is cached, regardless of HTTP method or user content. Some endpoints (e.g., POST, PUT) might not be safe or desirable to cache. Double-check whether restricting caching to GET or idempotent requests is necessary to prevent stale or incorrect responses for other request methods.

src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Extensions/ISharedServiceCollectionExtensions.cs (1)

43-43: In-memory cache registration is appropriate.

Registering memory caching here is consistent with the new caching features. This ensures that IMemoryCache is readily available for the CacheDelegatingHandler and other caching needs.

src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Web/Services/AppResponseCachePolicy.cs (4)

38-40: Renaming to clientCacheTtl clarifies caching scope.

Replacing browserCacheTtl with clientCacheTtl more accurately reflects multi-platform clients. No issues identified with the rename itself.


62-64: Disabling edge/client caching for pre-rendered pages is consistent.

This aligns with the comment about not supporting culture-specific variations on edge/client caches. The logic remains coherent with the existing code flow.


73-81: Conditional client/edge cache directives look good.

The code properly updates the response headers with either MaxAge or SharedMaxAge based on clientCacheTtl and edgeCacheTtl. This approach is consistent with the revised nomenclature.


95-95: Verify exposure of caching details in response headers.

The header "App-Cache-Response" reveals caching statuses (Output, Edge, and Client) to the client. If this is an intentional transparency feature, it’s fine; otherwise, consider removing or restricting it.

src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Services/AppResponseCachePolicy.cs (2)

38-38: LGTM! Consistent terminology update from 'browser' to 'client' cache.

The renaming provides better clarity as the caching can occur at any client level, not just browsers.

Also applies to: 65-65, 99-99


62-63:

Details

❓ Verification inconclusive

Verify the comment about cache variations.

The comment states that edge and client caches don't support culture variations. Please verify this limitation is still accurate with your current caching implementation.


🌐 Web query:

Do HTTP caches (CDN/edge/client) support variations by Accept-Language or custom culture headers?

💡 Result:

HTTP caches (CDN/edge/client) can support content variations based on Accept-Language or custom culture headers through mechanisms like the Vary header and vendor-specific implementations. Here’s how different caching layers handle this:


1. Standard Vary Header Support

Most HTTP caches use the Vary header to determine whether a cached response matches a new request based on specified request headers:

  • Accept-Language:
    Supported by most CDNs (e.g., Fastly [1], Google Cloud CDN [5], and Varnish [4]) and browsers when paired with Vary: Accept-Language. For example:

    Vary: Accept-Language

    This ensures separate cached versions for different language preferences.

  • Custom Headers:
    Possible via Vary: X-Custom-Header, but many CDNs restrict high-cardinality headers (e.g., User-Agent, Cookie) due to cache fragmentation risks. For example:

    Vary: X-Culture

    Google Cloud CDN explicitly blocks certain headers ([5]), while Netlify allows custom rules via Netlify-Vary ([2]).


2. Browser Caching Behavior

Browsers treat Vary as a validator rather than storing multiple variants:

  • Only one variant per URL is cached (e.g., storing responses for en-US but not fr-FR simultaneously) ([1]).
  • Ignored for HTTP/2 Server Push resources ([1]).

3. CDN/Edge-Specific Implementations

Netlify

Supports granular control via Netlify-Vary, enabling variations by:

  • Language groups:
    Netlify-Vary: language=en|de
  • Country groups:
    Netlify-Vary: country=us|ca+mx
  • Custom query/headers/cookies ([2]).

Google Cloud CDN

Restricts high-cardinality headers by default but allows:

  • Custom cache keys via includeHeaders configuration.
  • Overrides using FORCE_CACHE_ALL mode (ignores origin’s Cache-Control but respects Vary) ([5]).

Cloudflare

Historically lacked full Vary support ([3]), but recent updates may offer limited implementations (not covered in sources).


4. Best Practices

  • Use standard headers like Accept-Language instead of custom ones where possible.
  • Avoid overusing Vary: Multiple variants reduce cache efficiency.
  • For multilingual sites:
    • Prefer URL-based localization (/en/page, /fr/page) for better caching.
    • Use Key or Variants proposals (experimental) for smarter variation grouping ([1]).

Summary Table

Cache Type Supports Accept-Language? Supports Custom Headers? Notes
Browsers Yes (as validator) Limited Stores only one variant per URL ([1]).
Fastly Yes Yes Uses standard Vary logic ([1]).
Netlify Yes Yes Customizable via Netlify-Vary ([2]).
Google Cloud CDN Partial Partial Blocks high-cardinality headers by default; configurable ([5]).
Cloudflare Limited Limited Partial/no native support historically; check latest docs ([3]).

For dynamic content requiring culture-specific variations, combine HTTP caching with edge/serverless logic or use frameworks like Next.js that automate header-based caching optimizations ([2][7]).

Citations:


Action: Revisit our caching strategy regarding culture-specific variations.

It turns out that most HTTP caches—especially CDN and edge caches—can support content variations based on headers like Accept-Language (and even custom headers) when configured correctly (e.g., via the Vary header). However, note that browser caches generally store a single variant per URL regardless of the Vary header.

  • CDN/Edge Caching: Modern CDNs such as Fastly, Google Cloud CDN, and Netlify can be configured to accommodate such variations. This suggests that the blanket statement about edge caches not supporting culture variations may no longer apply universally.
  • Client (Browser) Caching: Browsers typically cache only one variant per URL, so the limitation for client-side caching remains valid.

Given these nuances, please verify that our current configuration for pre-rendered pages correctly reflects these realities. If our CDN is set up to handle Vary-based variations, it might be beneficial to re-enable edge caching (while continuing to treat browser caching with caution) so as to fully leverage caching across layers.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs (2)

85-85: LGTM! Appropriate service registration.

Registering CacheDelegatingHandler as scoped ensures each HTTP client scope gets its own handler instance.


76-81:

Details

❓ Verification inconclusive

Verify the caching handler's position in the chain.

The CacheDelegatingHandler is positioned after logging but before auth/retry/exception handling, which is a good order as it:

  1. Ensures cache operations are logged
  2. Can serve cached responses before hitting auth/retry logic
  3. Avoids caching error responses

However, please verify that this order doesn't cache unauthorized responses.


🏁 Script executed:

#!/bin/bash
# Search for cache-related logic in CacheDelegatingHandler
ast-grep --pattern 'class CacheDelegatingHandler {
  $$$
  SendAsync($_, $_) {
    $$$
  }
}'

Length of output: 211


Verify Caching Behavior in Handler Chain

The ordering in the IClientCoreServiceCollectionExtensions looks sound—placing the CacheDelegatingHandler after logging and before auth/retry/exception handling enables logging of cache operations and early serving of cached responses. However, due to non-conclusive automated output (an error reading a non-UTF8 file interfered with our script), please manually verify the implementation of CacheDelegatingHandler.SendAsync to ensure that unauthorized responses (or other error statuses) are not cached.

  • Action Required:
    • Manually inspect the SendAsync method in CacheDelegatingHandler to confirm that caching is bypassed for unauthorized (401) responses or other error cases, if applicable.
    • Ensure that caching behavior aligns with the intended order in the handler chain.
src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Boilerplate.Shared.csproj (1)

11-11:

Details

❓ Verification inconclusive

Verify the Microsoft.Extensions.Caching.Memory package version.

The package is correctly added for in-memory caching support. Since no version is specified, please verify that the central package management uses a compatible version.


🏁 Script executed:

#!/bin/bash
# Search for central package version management file
fd --type f "Directory.Packages.props" --exec cat {} \; | grep -A 5 "Microsoft.Extensions.Caching.Memory"

Length of output: 106


Action Required: Verify Central Package Version Configuration for Microsoft.Extensions.Caching.Memory

The automated search did not find any version information for the Microsoft.Extensions.Caching.Memory package in the central package management file (Directory.Packages.props). Please manually verify whether a compatible version is defined in your central package configuration. If no version is managed centrally, consider specifying an explicit version in the project file to ensure consistent caching behavior.

@msynk msynk merged commit c4929be into bitfoundation:develop Feb 15, 2025
3 checks passed
@yasmoradi yasmoradi deleted the 9897 branch February 15, 2025 09:49
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.

In-Memory response cache delegating handler is missing in the Boilerplate project template

2 participants