Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Reenable party list cache, log party name look failure with negative cache TTL #1395

Merged
merged 2 commits into from
Nov 21, 2024

Conversation

elsand
Copy link
Collaborator

@elsand elsand commented Nov 5, 2024

Description

Party list cache was by a mistake disabled, this reenables it. Also, add a log entry when party name lookup fails due to remote API response indicates no name (usually due to missing party profile). Cache negative responses for just 10 seconds (instead of the default 24 hours).

Related Issue(s)

  • N/A

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Summary by CodeRabbit

  • New Features

    • Enhanced caching for retrieving authorized parties, improving efficiency.
    • Introduced logging capabilities in the Party Name Registry client for better error tracking.
  • Bug Fixes

    • Improved error handling in the Party Name Registry client to log issues with missing names.
  • Refactor

    • Updated caching strategy in the Party Name Registry client for optimized performance.

@elsand elsand requested a review from a team as a code owner November 5, 2024 22:59
@elsand elsand changed the title Reenable party list cache, log party name look failure with negative cache TTL fix: Reenable party list cache, log party name look failure with negative cache TTL Nov 5, 2024
Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces modifications to two classes: AltinnAuthorizationClient and PartyNameRegistryClient. In AltinnAuthorizationClient, caching has been reinstated for the GetAuthorizedParties method to optimize data retrieval. In PartyNameRegistryClient, a new logger dependency has been added to the constructor, enhancing error handling and logging capabilities. The caching mechanism in GetName has also been refined to include a short negative cache duration when no name is retrieved. Overall, these changes focus on improving efficiency and error visibility without altering public method signatures.

Changes

File Change Summary
src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/Authorization/AltinnAuthorizationClient.cs Reinstated caching in GetAuthorizedParties method by uncommenting cache retrieval line; minor formatting adjustments made.
src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/NameRegistry/PartyNameRegistryClient.cs Added ILogger<PartyNameRegistryClient> to constructor; updated GetName method for specific caching and error handling; logged errors in GetNameFromRegister method.

Possibly related PRs

Suggested reviewers

  • MagnusSandgren

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 64a86dd and e36747b.

📒 Files selected for processing (1)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/Authorization/AltinnAuthorizationClient.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/Authorization/AltinnAuthorizationClient.cs

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

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/Authorization/AltinnAuthorizationClient.cs (2)

Line range hint 1-215: Consider splitting caching responsibilities.

The class currently handles both PDP and parties caching, which could be separated to follow the Single Responsibility Principle. Consider extracting the caching logic into dedicated cache providers for better maintainability and testability.

This would allow for:

  • Independent cache configuration for different concerns
  • Easier testing of caching strategies
  • More focused error handling

Line range hint 134-139: Enhance error logging for cache misses.

Consider adding detailed logging when no authorized parties are returned. This would help track the frequency and context of cache misses, especially for cases of missing Altinn profiles.

 if (authorizedPartiesDto is null || authorizedPartiesDto.Count == 0)
 {
+    _logger.LogWarning(
+        "No authorized parties returned for request {@Request}. This may indicate a missing Altinn profile.",
+        authorizedPartiesRequest);
     throw new UpstreamServiceException("access-management returned no authorized parties, missing Altinn profile?");
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 493d247 and 64a86dd.

📒 Files selected for processing (2)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/Authorization/AltinnAuthorizationClient.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/NameRegistry/PartyNameRegistryClient.cs (3 hunks)
🔇 Additional comments (5)
src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/Authorization/AltinnAuthorizationClient.cs (1)

84-85: LGTM! Verify cache configuration.

The reactivation of caching for authorized parties aligns with the PR objectives. The implementation looks correct and maintains proper error handling through PerformAuthorizedPartiesRequest.

Let's verify the cache configuration to ensure it aligns with the PR objectives:

✅ Verification successful

Cache configuration verified and properly implemented

The cache implementation for authorized parties is correctly configured with appropriate TTL and security measures:

  • Cache duration is set to 15 minutes (TimeSpan.FromMinutes(15))
  • Cache key generation is secure using SHA256 hashing
  • Memory cache is enabled for authorized parties since it has low cardinality
  • Redis is configured as distributed cache with proper backplane setup

The implementation aligns perfectly with the PR objectives of reenabling party list cache.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify cache configuration and key generation
# Test 1: Look for cache configuration
rg -l "FusionCache.*Configuration.*TTL"

# Test 2: Verify the cache key generation implementation
ast-grep --pattern 'GenerateCacheKey()' 

Length of output: 83


Script:

#!/bin/bash
# Let's try different approaches to find cache configuration and key generation

# Look for cache configuration with broader patterns
rg -A 5 "FusionCache|CacheOptions|TTL" 

# Look for cache key generation method with broader pattern
ast-grep --pattern 'public string GenerateCacheKey'

# Look for the request class that might contain the key generation
rg -A 5 "AuthorizedPartiesRequest"

# Look for cache setup in startup/configuration
rg -A 5 "AddFusionCache|ConfigureFusionCache"

Length of output: 29543

src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/NameRegistry/PartyNameRegistryClient.cs (4)

7-7: Approved: Added logging dependency

The inclusion of using Microsoft.Extensions.Logging; integrates the logging capabilities required for enhanced error handling.


16-16: Approved: Declared logger field

The declaration of the logger field _logger is appropriate and follows best practices for dependency injection.


24-27: Approved: Updated constructor with logger injection

The constructor correctly injects the ILogger<PartyNameRegistryClient> dependency and includes a null check, ensuring robustness.


33-45: Approved: Enhanced caching mechanism with negative caching

The use of GetOrSetAsync<string?> with a specified type parameter improves clarity. The implementation of a short negative cache for null results optimizes performance for missing data scenarios.

@oskogstad oskogstad merged commit d18bb76 into main Nov 21, 2024
21 of 24 checks passed
@oskogstad oskogstad deleted the fix/cache-fixes branch November 21, 2024 14:16
arealmaas pushed a commit that referenced this pull request Nov 25, 2024
🤖 I have created a release *beep* *boop*
---


##
[1.39.0](v1.38.0...v1.39.0)
(2024-11-22)


### Features

* **azure:** adjust SKU and storage for yt01 and prod
([b7e4909](b7e4909))
* **azure:** adjust SKU and storage for yt01 and prod
([#1508](#1508))
([5478275](5478275))
* **graphql:** Create separate type for sub-parties
([#1510](#1510))
([9c75f11](9c75f11))


### Bug Fixes

* **azure:** ensure correct properties are used when adjusting SKU and
storage for postgres
([#1514](#1514))
([c51d2f5](c51d2f5))
* Reenable party list cache, log party name look failure with negative
cache TTL ([#1395](#1395))
([d18bb76](d18bb76))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
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.

3 participants