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

Added caching of AuthroizedParties to GetAuthorizedParties #606

Merged
merged 3 commits into from
Jan 22, 2025

Conversation

axely123
Copy link
Contributor

@axely123 axely123 commented Jan 20, 2025

Description

Performance tests have revealed that the call to the AccessManagement API is a performance bottleneck. To address this, this PR introduces caching of AuthorizedParties to the AccessManagment service. By caching this data, unnecessary API calls are avoided, which helps reduce latency and significantly improve overall system performance.

Related Issue(s)

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)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

Summary by CodeRabbit

  • Performance Improvements
    • Added caching mechanism for authorized parties retrieval.
    • Reduced external service calls by implementing distributed cache.
    • Cached party data expires after 15 minutes.
    • Implemented error handling for cache retrieval and storage.

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

📝 Walkthrough

Walkthrough

The pull request introduces caching functionality to the AltinnAccessManagementService class in the Altinn Correspondence project. By adding IDistributedCache as a constructor dependency, the service can now cache authorized parties' data with a 15-minute expiration time. The GetAuthorizedParties method is enhanced to first check the cache for existing data, and if not found, retrieve the data from the external service and then store it in the cache for future requests. Error handling for cache operations is also included.

Changes

File Change Summary
src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs - Added IDistributedCache to constructor
- Implemented caching logic in GetAuthorizedParties method
- Added cache key generation and serialization/deserialization of cached data
- Included error handling for cache retrieval and storage

Possibly related PRs

Suggested labels

kind/enhancement, kind/chore

Suggested reviewers

  • RagnarFatland-Avanade

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 12b8c84 and 85ee809.

📒 Files selected for processing (1)
  • src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.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 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
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: 2

🧹 Nitpick comments (2)
src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs (2)

7-7: Consider extracting caching logic to a decorator pattern.

The current implementation mixes caching responsibility with the core service logic, violating the Single Responsibility Principle. Consider:

  1. Implementing a decorator pattern to separate caching concerns
  2. Moving cache configuration to application settings

Example decorator pattern implementation:

public class CachedAltinnAccessManagementService : IAltinnAccessManagementService
{
    private readonly IAltinnAccessManagementService _inner;
    private readonly IDistributedCache _cache;
    private readonly DistributedCacheEntryOptions _cacheOptions;

    public CachedAltinnAccessManagementService(
        IAltinnAccessManagementService inner,
        IDistributedCache cache,
        IOptions<CacheOptions> cacheOptions)
    {
        _inner = inner;
        _cache = cache;
        _cacheOptions = new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = cacheOptions.Value.ExpirationTime
        };
    }
    
    // Implement caching logic here, delegating to _inner for actual work
}

Also applies to: 20-21


Line range hint 72-81: Improve error handling with specific exceptions.

The error handling could be more specific and informative.

Consider creating custom exceptions:

public class AccessManagementException : Exception
{
    public HttpStatusCode StatusCode { get; }
    
    public AccessManagementException(HttpStatusCode statusCode, string message, Exception? inner = null) 
        : base($"Access Management API error: {message}. Status code: {statusCode}", inner)
    {
        StatusCode = statusCode;
    }
}

Then update the error handling:

 if (!response.IsSuccessStatusCode)
 {
-    _logger.LogError(await response.Content.ReadAsStringAsync(cancellationToken));
-    _logger.LogError("Error code in call against Authorization GetAuthorizedParties");
-    throw new Exception("Error code in call against Authorization GetAuthorizedParties: " + response.StatusCode);
+    var content = await response.Content.ReadAsStringAsync(cancellationToken);
+    _logger.LogError("Failed to get authorized parties. Status: {StatusCode}, Content: {Content}", 
+        response.StatusCode, content);
+    throw new AccessManagementException(response.StatusCode, content);
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7ef949d and 3ac8f9f.

📒 Files selected for processing (1)
  • src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs (4 hunks)
🔇 Additional comments (1)
src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs (1)

Line range hint 72-81: Fix typo in class name "AuthroizedPartiesResponse".

The class name contains a typo: "Authroized" should be "Authorized".

Apply this diff:

- internal sealed class AuthroizedPartiesResponse
+ internal sealed class AuthorizedPartiesResponse

Remember to update all references to this class name in the codebase.

✅ Verification successful

Typo fix is isolated to a single file

The typo in "AuthroizedPartiesResponse" only needs to be fixed in AltinnAccessManagementService.cs. Since the class is internal and all references are contained within this file, no other files in the codebase will be impacted by this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all occurrences of the typo in the codebase
rg "Authroized" --type cs

Length of output: 578

…prevent application crash on cache failure
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: 0

♻️ Duplicate comments (1)
src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs (1)

23-36: 🛠️ Refactor suggestion

Add null checks and externalize cache configuration.

The constructor needs validation for injected dependencies and the cache expiration time should be configurable.

This is a duplicate of a previous review comment. The suggested improvements include:

  1. Adding null checks for all dependencies
  2. Externalizing cache configuration
  3. Proper initialization order
🧹 Nitpick comments (1)
src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs (1)

Line range hint 74-93: Enhance cache storage reliability and performance.

While basic error handling is in place, the implementation could benefit from additional reliability features.

Consider implementing:

  1. Retry mechanism for transient cache failures
  2. Background cache refresh to prevent cache stampede
  3. Sliding cache expiration for frequently accessed items

Example implementation for retry mechanism:

+private async Task SetCacheWithRetryAsync(string key, string value, DistributedCacheEntryOptions options, CancellationToken cancellationToken)
+{
+    const int maxRetries = 3;
+    for (int i = 0; i < maxRetries; i++)
+    {
+        try
+        {
+            await _cache.SetStringAsync(key, value, options, cancellationToken);
+            return;
+        }
+        catch (Exception ex) when (i < maxRetries - 1)
+        {
+            _logger.LogWarning(ex, $"Failed to set cache (attempt {i + 1}/{maxRetries})");
+            await Task.Delay(TimeSpan.FromMilliseconds(100 * Math.Pow(2, i)), cancellationToken);
+        }
+    }
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ac8f9f and 12b8c84.

📒 Files selected for processing (1)
  • src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs (4 hunks)
🔇 Additional comments (2)
src/Altinn.Correspondence.Integrations/Altinn/AccessManagement/AltinnAccessManagementService.cs (2)

7-7: LGTM! Necessary additions for caching implementation.

The using statement and field declarations are correctly added to support distributed caching functionality.

Also applies to: 20-21


41-53: 🛠️ Refactor suggestion

Improve cache key construction and error handling.

The current cache key construction needs improvement to handle special characters and potential conflicts.

Apply this diff to improve the implementation:

-string cacheKey = $"AuthorizedParties_{partyToRequestFor.PartyId}";
+string cacheKey = $"altinn:correspondence:authorizedparties:{partyToRequestFor.PartyId}";

Consider adding:

  1. Key prefix to prevent conflicts with other services
  2. Key sanitization to handle special characters
  3. Key length validation

Likely invalid or redundant comment.

@Ceredron Ceredron linked an issue Jan 21, 2025 that may be closed by this pull request
Copy link
Collaborator

@Ceredron Ceredron left a comment

Choose a reason for hiding this comment

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

Looks good!

@axely123 axely123 merged commit de685f9 into main Jan 22, 2025
3 checks passed
@axely123 axely123 deleted the feat/cache-accessmanagment-call branch January 22, 2025 09:35
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 AccessManagement kall i Redis
2 participants