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

chore: Fix redundant call to resource registry API #1181

Merged
merged 8 commits into from
Sep 26, 2024

Conversation

knuhau
Copy link
Collaborator

@knuhau knuhau commented Sep 24, 2024

Description

This is due to the application caching two separate dictionaries of info from the resource registry, grouped by different keys.

CleanShot 2024-09-25 at 15 30 41@2x

Added caching of the raw response from the resource registry and removed the dependent caches to lower complexity.

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)

Documentation

  • Documentation is updated (either in docs-directory, Altinnpedia or a separate linked PR in altinn-studio-docs., if applicable)

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Improved caching strategy for service resource information retrieval, enhancing performance and efficiency.
    • Centralized data fetching logic for service resources, allowing for more streamlined and efficient access.
  • Bug Fixes

    • Streamlined data fetching logic to minimize unnecessary calls to the endpoint by utilizing the updated caching mechanism.

@knuhau knuhau requested a review from a team as a code owner September 24, 2024 08:58
Copy link
Contributor

coderabbitai bot commented Sep 24, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request modifies the ResourceRegistryClient class in the ResourceRegistryClient.cs file. A new constant, ServiceResourceInformationCacheKey, has been introduced. The methods for retrieving resource information by organization and by resource ID have been removed, with their logic integrated into the FetchServiceResourceInformation method. This method now centralizes caching using _cache.GetOrSetAsync to fetch or retrieve cached service resource information. The endpoint for fetching updated subject resources has also been updated.

Changes

File Path Change Summary
src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/ResourceRegistry/ResourceRegistryClient.cs Introduced ServiceResourceInformationCacheKey, removed methods for fetching resource info by organization and ID, and updated FetchServiceResourceInformation for centralized caching.

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: 3

Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between e0c1cf2 and 732ab84.

Files selected for processing (1)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/ResourceRegistry/ResourceRegistryClient.cs (2 hunks)
Additional comments not posted (2)
src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/ResourceRegistry/ResourceRegistryClient.cs (2)

12-12: Addition of Cache Key is Appropriate

The new cache key ServiceResourceInformationCacheKey is well-named and consistent with the existing cache keys.


103-123: Efficient Caching Implementation

Caching the result of FetchServiceResourceInformation using _cache.GetOrSetAsync effectively minimizes redundant API calls to the resource registry, enhancing performance as intended.

…egistry/ResourceRegistryClient.cs

Co-authored-by: Ole Jørgen Skogstad <[email protected]>
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

Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 732ab84 and 8fa5c20.

Files selected for processing (1)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/ResourceRegistry/ResourceRegistryClient.cs (2 hunks)
Additional comments not posted (4)
src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/ResourceRegistry/ResourceRegistryClient.cs (4)

12-12: LGTM!

The addition of the new cache key constant ServiceResourceInformationCacheKey is appropriate and follows the naming conventions.


103-126: ⚠️ Potential issue

Specify Cache Expiration Policy for Freshness

Currently, the cache duration for ServiceResourceInformationCacheKey is not explicitly defined. To ensure that the cached service resource information remains up-to-date with the resource registry, consider specifying a cache expiration policy.

You can set the cache duration by providing cache options:

 return await _cache.GetOrSetAsync(
     ServiceResourceInformationCacheKey,
     async cToken =>
     {
         // existing code
     },
+    options: new FusionCacheEntryOptions
+    {
+        Duration = TimeSpan.FromMinutes(30) // Set an appropriate duration
+    },
     token: cancellationToken);

107-109: ⚠️ Potential issue

Ensure Exception Handling Within Cache Delegate

The previous concern about exception handling within the cache delegate remains valid. If an exception occurs during the data fetch, it might affect the cache state or propagate unintended exceptions. Ensure exceptions are properly handled within the cache delegate to maintain cache integrity.

Consider wrapping the HTTP request in a try-catch block:

 return await _cache.GetOrSetAsync(
     ServiceResourceInformationCacheKey,
     async cToken =>
     {
+        try
+        {
             var response = await _client
                 .GetFromJsonEnsuredAsync<List<ResourceListResponse>>(searchEndpoint,
                     cancellationToken: cToken);

+            // existing code
+        }
+        catch (Exception ex)
+        {
+            // Handle exception or rethrow with additional context
+            throw new InvalidOperationException("Failed to fetch service resource information.", ex);
+        }
     },
     token: cancellationToken);

103-126: 🛠️ Refactor suggestion

Consider Redundancy of Multiple Caching Layers

Caching is now implemented in FetchServiceResourceInformation, and there are additional caches in GetOrSetResourceInformationByOrg and GetOrSetResourceInformationByResourceId. This might introduce redundant caching layers.

Evaluate whether caching at both levels is necessary. If the data transformation in the higher-level methods is minimal, you might simplify by relying solely on the lower-level cache to reduce complexity.

Copy link

sonarcloud bot commented Sep 26, 2024

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: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 8aa1be5 and e09c895.

📒 Files selected for processing (1)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/ResourceRegistry/ResourceRegistryClient.cs (3 hunks)
🔇 Additional comments (3)
src/Digdir.Domain.Dialogporten.Infrastructure/Altinn/ResourceRegistry/ResourceRegistryClient.cs (3)

10-14: Consistent Naming of Constants

The addition of ServiceResourceInformationCacheKey and ResourceRegistryResourceEndpoint constants enhances maintainability by centralizing important strings. This is a good practice that improves the readability and manageability of the code.


29-32: Efficient Retrieval of Resources by Organization

The method GetResourceInformationForOrg now efficiently retrieves resources by filtering the cached data based on OwnerOrgNumber. This change reduces redundant API calls and simplifies the code.


39-41: Simplified Retrieval of Resource Information by ID

The method GetResourceInformation directly retrieves the desired resource from the cached data using FirstOrDefault, improving performance and reducing complexity.

Comment on lines +29 to +41
var resources = await FetchServiceResourceInformation(cancellationToken);
return resources
.Where(x => x.OwnerOrgNumber == orgNumber)
.ToList();
}

public async Task<ServiceResourceInformation?> GetResourceInformation(
string serviceResourceId,
CancellationToken cancellationToken)
{
var dic = await GetOrSetResourceInformationByResourceId(cancellationToken);
dic.TryGetValue(serviceResourceId, out var resource);
return resource;
var resources = await FetchServiceResourceInformation(cancellationToken);
return resources
.FirstOrDefault(x => x.ResourceId == serviceResourceId);
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider Adding Unit Tests to Validate Resource Retrieval Methods

Adding unit tests for GetResourceInformationForOrg and GetResourceInformation will help ensure that the filtering and retrieval logic works correctly, and it will prevent future regressions.

Do you need assistance in writing these unit tests, or would you like me to open a new GitHub issue to track this task?

Comment on lines +66 to +88
private async Task<ServiceResourceInformation[]> FetchServiceResourceInformation(CancellationToken cancellationToken)
{
return await _cache.GetOrSetAsync(
ServiceResourceInformationByOrgCacheKey,
async cToken =>
{
var resources = await FetchServiceResourceInformation(cToken);
return resources
.GroupBy(x => x.OwnerOrgNumber)
.ToDictionary(x => x.Key, x => x.ToArray());
},
token: cancellationToken);
}
const string searchEndpoint = $"{ResourceRegistryResourceEndpoint}resourcelist";

private async Task<Dictionary<string, ServiceResourceInformation>> GetOrSetResourceInformationByResourceId(
CancellationToken cancellationToken)
{
return await _cache.GetOrSetAsync(
ServiceResourceInformationByResourceIdCacheKey,
ServiceResourceInformationCacheKey,
async cToken =>
{
var resources = await FetchServiceResourceInformation(cToken);
return resources.ToDictionary(x => x.ResourceId);
var response = await _client
.GetFromJsonEnsuredAsync<List<ResourceListResponse>>(searchEndpoint,
cancellationToken: cToken);

return response
.Where(x => !string.IsNullOrWhiteSpace(x.HasCompetentAuthority.Organization))
.Where(x => x.ResourceType is
ResourceTypeGenericAccess or
ResourceTypeAltinnApp or
ResourceTypeCorrespondence)
.Select(x => new ServiceResourceInformation(
$"{Constants.ServiceResourcePrefix}{x.Identifier}",
x.ResourceType,
x.HasCompetentAuthority.Organization!))
.ToArray();
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider Filtering Resources at the API Level to Improve Performance

In FetchServiceResourceInformation, all resources are fetched and then filtered in-memory. If the number of resources is large, this could lead to performance issues due to the amount of data being transferred and processed.

Consider modifying the API request to include query parameters that filter resources on the server side. This would reduce the amount of data transferred over the network and minimize in-memory processing.

For example, adjust the searchEndpoint to include filters:

-const string searchEndpoint = $"{ResourceRegistryResourceEndpoint}resourcelist";
+const string searchEndpoint = $"{ResourceRegistryResourceEndpoint}resourcelist?filter=ResourceType:{ResourceTypeGenericAccess},{ResourceTypeAltinnApp},{ResourceTypeCorrespondence}";

Ensure that the API supports filtering by ResourceType and that HasCompetentAuthority.Organization is not null or empty.

Committable suggestion was skipped due to low confidence.


🛠️ Refactor suggestion

Consider Specifying Cache Expiration Policy for Freshness

The cache duration for ServiceResourceInformationCacheKey is not explicitly defined. To keep the cached service resource information up-to-date with the resource registry, consider specifying a cache expiration policy.

You can set the cache duration by providing cache options:

return await _cache.GetOrSetAsync(
    ServiceResourceInformationCacheKey,
    async cToken =>
    {
        // existing code
    },
+   options: new FusionCacheEntryOptions
+   {
+       Duration = TimeSpan.FromMinutes(30) // Set an appropriate duration
+   },
    token: cancellationToken);

This ensures that the cache refreshes periodically, keeping the data current.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private async Task<ServiceResourceInformation[]> FetchServiceResourceInformation(CancellationToken cancellationToken)
{
return await _cache.GetOrSetAsync(
ServiceResourceInformationByOrgCacheKey,
async cToken =>
{
var resources = await FetchServiceResourceInformation(cToken);
return resources
.GroupBy(x => x.OwnerOrgNumber)
.ToDictionary(x => x.Key, x => x.ToArray());
},
token: cancellationToken);
}
const string searchEndpoint = $"{ResourceRegistryResourceEndpoint}resourcelist";
private async Task<Dictionary<string, ServiceResourceInformation>> GetOrSetResourceInformationByResourceId(
CancellationToken cancellationToken)
{
return await _cache.GetOrSetAsync(
ServiceResourceInformationByResourceIdCacheKey,
ServiceResourceInformationCacheKey,
async cToken =>
{
var resources = await FetchServiceResourceInformation(cToken);
return resources.ToDictionary(x => x.ResourceId);
var response = await _client
.GetFromJsonEnsuredAsync<List<ResourceListResponse>>(searchEndpoint,
cancellationToken: cToken);
return response
.Where(x => !string.IsNullOrWhiteSpace(x.HasCompetentAuthority.Organization))
.Where(x => x.ResourceType is
ResourceTypeGenericAccess or
ResourceTypeAltinnApp or
ResourceTypeCorrespondence)
.Select(x => new ServiceResourceInformation(
$"{Constants.ServiceResourcePrefix}{x.Identifier}",
x.ResourceType,
x.HasCompetentAuthority.Organization!))
.ToArray();
private async Task<ServiceResourceInformation[]> FetchServiceResourceInformation(CancellationToken cancellationToken)
{
const string searchEndpoint = $"{ResourceRegistryResourceEndpoint}resourcelist";
return await _cache.GetOrSetAsync(
ServiceResourceInformationCacheKey,
async cToken =>
{
var response = await _client
.GetFromJsonEnsuredAsync<List<ResourceListResponse>>(searchEndpoint,
cancellationToken: cToken);
return response
.Where(x => !string.IsNullOrWhiteSpace(x.HasCompetentAuthority.Organization))
.Where(x => x.ResourceType is
ResourceTypeGenericAccess or
ResourceTypeAltinnApp or
ResourceTypeCorrespondence)
.Select(x => new ServiceResourceInformation(
$"{Constants.ServiceResourcePrefix}{x.Identifier}",
x.ResourceType,
x.HasCompetentAuthority.Organization!))
.ToArray();
},
options: new FusionCacheEntryOptions
{
Duration = TimeSpan.FromMinutes(30) // Set an appropriate duration
},
token: cancellationToken);

⚠️ Potential issue

Ensure Exception Handling Within Cache Delegate

If an exception occurs during the HTTP request in FetchServiceResourceInformation, it could affect cache integrity or propagate unintended exceptions. To maintain stability, consider adding exception handling within the cache delegate.

Wrap the HTTP request in a try-catch block:

return await _cache.GetOrSetAsync(
    ServiceResourceInformationCacheKey,
    async cToken =>
    {
+       try
+       {
            var response = await _client
                .GetFromJsonEnsuredAsync<List<ResourceListResponse>>(searchEndpoint,
                    cancellationToken: cToken);

            return response
                .Where(x => !string.IsNullOrWhiteSpace(x.HasCompetentAuthority.Organization))
                .Where(x => x.ResourceType is
                    ResourceTypeGenericAccess or
                    ResourceTypeAltinnApp or
                    ResourceTypeCorrespondence)
                .Select(x => new ServiceResourceInformation(
                    $"{Constants.ServiceResourcePrefix}{x.Identifier}",
                    x.ResourceType,
                    x.HasCompetentAuthority.Organization!))
                .ToArray();
+       }
+       catch (Exception ex)
+       {
+           // Handle exception appropriately
+           throw new InvalidOperationException("Failed to fetch service resource information.", ex);
+       }
    },
    token: cancellationToken);

This ensures that any exceptions are properly handled, and the cache remains consistent.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private async Task<ServiceResourceInformation[]> FetchServiceResourceInformation(CancellationToken cancellationToken)
{
return await _cache.GetOrSetAsync(
ServiceResourceInformationByOrgCacheKey,
async cToken =>
{
var resources = await FetchServiceResourceInformation(cToken);
return resources
.GroupBy(x => x.OwnerOrgNumber)
.ToDictionary(x => x.Key, x => x.ToArray());
},
token: cancellationToken);
}
const string searchEndpoint = $"{ResourceRegistryResourceEndpoint}resourcelist";
private async Task<Dictionary<string, ServiceResourceInformation>> GetOrSetResourceInformationByResourceId(
CancellationToken cancellationToken)
{
return await _cache.GetOrSetAsync(
ServiceResourceInformationByResourceIdCacheKey,
ServiceResourceInformationCacheKey,
async cToken =>
{
var resources = await FetchServiceResourceInformation(cToken);
return resources.ToDictionary(x => x.ResourceId);
var response = await _client
.GetFromJsonEnsuredAsync<List<ResourceListResponse>>(searchEndpoint,
cancellationToken: cToken);
return response
.Where(x => !string.IsNullOrWhiteSpace(x.HasCompetentAuthority.Organization))
.Where(x => x.ResourceType is
ResourceTypeGenericAccess or
ResourceTypeAltinnApp or
ResourceTypeCorrespondence)
.Select(x => new ServiceResourceInformation(
$"{Constants.ServiceResourcePrefix}{x.Identifier}",
x.ResourceType,
x.HasCompetentAuthority.Organization!))
.ToArray();
private async Task<ServiceResourceInformation[]> FetchServiceResourceInformation(CancellationToken cancellationToken)
{
const string searchEndpoint = $"{ResourceRegistryResourceEndpoint}resourcelist";
return await _cache.GetOrSetAsync(
ServiceResourceInformationCacheKey,
async cToken =>
{
try
{
var response = await _client
.GetFromJsonEnsuredAsync<List<ResourceListResponse>>(searchEndpoint,
cancellationToken: cToken);
return response
.Where(x => !string.IsNullOrWhiteSpace(x.HasCompetentAuthority.Organization))
.Where(x => x.ResourceType is
ResourceTypeGenericAccess or
ResourceTypeAltinnApp or
ResourceTypeCorrespondence)
.Select(x => new ServiceResourceInformation(
$"{Constants.ServiceResourcePrefix}{x.Identifier}",
x.ResourceType,
x.HasCompetentAuthority.Organization!))
.ToArray();
}
catch (Exception ex)
{
// Handle exception appropriately
throw new InvalidOperationException("Failed to fetch service resource information.", ex);
}
},
token: cancellationToken);

@oskogstad oskogstad merged commit 8e570b4 into main Sep 26, 2024
22 checks passed
@oskogstad oskogstad deleted the chore/redundant-call-resource-reg branch September 26, 2024 08:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

3 participants