Skip to content

fix: Ensure cache is updated immediately - #42

Merged
nielsenko merged 3 commits into
serverpod:mainfrom
nielsenko:use-raw-value-as-expando-key
Apr 7, 2025
Merged

nielsenko merged 3 commits into
serverpod:mainfrom
nielsenko:use-raw-value-as-expando-key

Conversation

@nielsenko

@nielsenko nielsenko commented Apr 3, 2025 •

Copy link
Copy Markdown
Collaborator

Description

Previously reading a value through a header accessor inside an update callback would in some cases be stale.
Example:

    final headers = Headers.build((mh) {
      mh.anInt = 42;
      expect(mh.anInt, 42); // first read goes well, since cache hangs of mh, but was empty for anInt
      mh.anInt = 1202;
      expect(mh.anInt, 1202); // <-- fail: second read would fail, cache still 42
    });
    // here cache is correct
    expect(headers.anInt, 1202);
  • test: Add failing tests
  • fix: Use raw-value as expando key, and update cache on set value

Related Issues

Fix: #45

Pre-Launch Checklist

Please ensure that your PR meets the following requirements before submitting:

  • This update focuses on a single feature or bug fix. (For multiple fixes, please submit separate PRs.)
  • I have read and followed the Dart Style Guide and formatted the code using dart format.
  • I have referenced at least one issue this PR fixes or is related to.
  • I have updated/added relevant documentation (doc comments with ///), ensuring consistency with existing project documentation.
  • I have added new tests to verify the changes.
  • All existing and new tests pass successfully.
  • I have documented any breaking changes below.

Breaking Changes

  • Includes breaking changes.
  • No breaking changes.

Summary by CodeRabbit

  • Refactor

    • Enhanced header processing with improved caching strategies for better performance and reliability.
  • Tests

    • Added test cases to ensure the caching logic works as intended, reducing redundant processing when header data remains unchanged.

@coderabbitai

coderabbitai Bot commented Apr 3, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto 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

Walkthrough

The changes update the caching mechanism in the header accessor component by introducing explicit type parameters and modifying caching keys. The _cache getter now returns Expando<T> instead of Expando, and the methods for setting and retrieving header values have been adjusted to better prime and query the cache. In addition, a new function wrapping int.parse has been added along with a counter variable to track the number of parse operations. Test cases have been introduced to verify that the cache is used appropriately, only re-parsing when the raw header value changes.

Changes

File Changes Summary
lib/src/headers/…/header_accessor.dart - Updated _cache getter to return Expando<T> for type safety.
- Modified getValueFrom to use the raw variable as the cache key.
- Updated setValueOn to call _setValue and cache its non-null result immediately.
- Changed _setValue return type from void to Iterable<String>?.
test/headers/…/headers_accessor_test.dart - Added a new function intParseAndCount which wraps int.parse, incrementing a global _count with each call.
- Declared a new variable _count to track parse calls.
- Introduced tests to ensure header values are correctly updated and that the parsing function is invoked only when the raw value changes.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Caller as Caller
    participant HA as HeaderAccessor
    participant Cache as Cache (Expando<T>)
    participant Headers as MutableHeaders

    Caller->>HA: setValueOn(Headers, value)
    HA->>HA: _setValue(Headers, key, value)
    HA->>Cache: Cache result if non-null
    Caller->>HA: getValueFrom(Headers)
    HA->>Cache: Retrieve cached value using raw key
    Cache-->>HA: Return cached header value
    HA-->>Caller: Return header value
Loading
sequenceDiagram
    autonumber
    participant Test as Test Case
    participant HA as HeaderAccessor
    participant Parser as intParseAndCount

    Test->>HA: Request header value (_anInt)
    HA->>Parser: intParseAndCount(rawValue)
    Parser-->>HA: Return parsed integer (increment _count)
    HA-->>Test: Return header value
Loading

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@codecov

codecov Bot commented Apr 3, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 78.53%. Comparing base (b0c6140) to head (f64efca).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #42      +/-   ##
==========================================
+ Coverage   78.43%   78.53%   +0.09%     
==========================================
  Files          70       70              
  Lines        2272     2273       +1     
  Branches     1181     1181              
==========================================
+ Hits         1782     1785       +3     
+ Misses        490      488       -2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nielsenko nielsenko changed the title fix:Ensure cache is updated immediately fix: Ensure cache is updated immediately Apr 3, 2025
@nielsenko
nielsenko force-pushed the use-raw-value-as-expando-key branch from 5de9caa to 37ba225 Compare April 3, 2025 17:18
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 3, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@nielsenko nielsenko self-assigned this Apr 3, 2025
@nielsenko
nielsenko requested a review from SandPod April 3, 2025 17:27
@nielsenko
nielsenko marked this pull request as ready for review April 3, 2025 17:32

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice fix! A couple of questions to understand the implementation and as always, comments around test structure 🔧 ⚒️

Comment thread test/headers/headers_accessor_test.dart Resolved
Comment thread test/headers/headers_accessor_test.dart Resolved
Comment thread test/headers/headers_accessor_test.dart Resolved
Comment thread test/headers/headers_accessor_test.dart Resolved
Comment thread lib/src/headers/header_accessor.dart Resolved
Comment thread lib/src/headers/header_accessor.dart Resolved
@nielsenko
nielsenko requested a review from SandPod April 4, 2025 15:09
@nielsenko nielsenko mentioned this pull request Apr 7, 2025

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! 🚀

Last non blocking suggestion to better reflect the "Given" of the test.

});
});

group('Given a header accessor ', () {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion(NIT): Change to Given a header accessor that counts decodes

@nielsenko
nielsenko merged commit 6df02d4 into serverpod:main Apr 7, 2025
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.

Cache may be stale while inside update callback

2 participants