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

Add ITranslationProvider.LoadTranslationsAsync() #15886

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

hishamco
Copy link
Member

Fixes #11356

No breaking changes

Copy link
Contributor

coderabbitai bot commented Apr 26, 2024

📝 Walkthrough

Walkthrough

The updates across OrchardCore's localization modules primarily focus on transitioning from synchronous to asynchronous methods. This shift enhances the system's efficiency by supporting non-blocking operations, especially beneficial when loading translations from various data stores. Key interfaces and classes within the localization framework have been refactored to include async methods, with corresponding deprecations of their synchronous counterparts.

Changes

File Path Summary of Changes
src/OrchardCore/OrchardCore.Localization.Abstractions/IPluralStringLocalizer.cs Modified IPluralStringLocalizer interface to include GetTranslation method directly within the interface definition, removing nested interfaces.
src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs
src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs
Updated PortableObjectHtmlLocalizer to use asynchronous method GetTranslationAsync and GetAwaiter().GetResult(). Converted synchronous methods to asynchronous in PortableObjectStringLocalizer.cs for improved performance and responsiveness.
src/OrchardCore/OrchardCore.Localization.Abstractions/ITranslationProvider.cs
src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs
src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs
src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoFilesTranslationsProvider.cs
Refactored interfaces and classes across these files to introduce asynchronous methods for loading translations, deprecating synchronous methods and enhancing performance through async operations.

Assessment against linked issues

Objective Addressed Explanation
Async support for loading translations (#11356)
Non-blocking operations for data stores (#11356)

The changes effectively address the primary objectives outlined in the linked issue #11356 by incorporating asynchronous methods across the localization interfaces and their implementations. This refactoring ensures that the system can handle translation loading operations asynchronously, thereby avoiding blocking calls and enhancing performance when interacting with various data storage solutions.


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

Comment on lines 74 to 75
? GetAllStringsFromCultureHierarchyAsync(culture)
: GetAllStringsAsync(culture).ToEnumerable();
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider maintaining asynchronous flow in GetAllStrings.

- : GetAllStringsAsync(culture).ToEnumerable();
+ : GetAllStringsAsync(culture);

This change avoids potential performance bottlenecks by not blocking the thread while converting IAsyncEnumerable to IEnumerable.


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.

Suggested change
? GetAllStringsFromCultureHierarchyAsync(culture)
: GetAllStringsAsync(culture).ToEnumerable();
? GetAllStringsFromCultureHierarchyAsync(culture)
: GetAllStringsAsync(culture);

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

Comment on lines 74 to 76
return includeParentCultures
? GetAllStringsFromCultureHierarchyAsync(culture).GetAwaiter().GetResult()
: GetAllStringsAsync(culture).ToEnumerable();
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider maintaining asynchronous flow in GetAllStrings.

- return includeParentCultures
-     ? GetAllStringsFromCultureHierarchyAsync(culture).GetAwaiter().GetResult()
-     : GetAllStringsAsync(culture).ToEnumerable();
+ return includeParentCultures
+     ? await GetAllStringsFromCultureHierarchyAsync(culture).ToListAsync()
+     : await GetAllStringsAsync(culture).ToListAsync();

This change avoids potential performance bottlenecks by not blocking the thread while converting IAsyncEnumerable to IEnumerable.


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.

Suggested change
return includeParentCultures
? GetAllStringsFromCultureHierarchyAsync(culture).GetAwaiter().GetResult()
: GetAllStringsAsync(culture).ToEnumerable();
return includeParentCultures
? await GetAllStringsFromCultureHierarchyAsync(culture).ToListAsync()
: await GetAllStringsAsync(culture).ToListAsync();

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

Copy link
Member

@Piedone Piedone left a comment

Choose a reason for hiding this comment

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

Since the ultimate consumers of these services, PortableObjectHtmlLocalizer and PortableObjectStringLocalizer retrieve the localization values synchronously, I doubt we get a performance benefit but there is a chance of deadlocks.

Please provide end-to-end benchmarks for these services so we can see if we gain something.

/// <inheritdoc />
public async Task<CultureDictionary> GetDictionaryAsync(CultureInfo culture)
{
var cachedDictionary = _cache.GetOrCreate(CacheKeyPrefix + culture.Name, k => new Lazy<Task<CultureDictionary>>(async () =>
Copy link
Member

Choose a reason for hiding this comment

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

This now caches not the dictionary but a Task that produces the dictionary. While this looks working at a first glance, this is not what should really happen. Rather, the dictionary itself needs to be cached. I don't think the Lazy makes sense here anyway.

Comment on lines +16 to +18
<ItemGroup>
<PackageReference Include="System.Linq.Async" />
</ItemGroup>
Copy link
Member

Choose a reason for hiding this comment

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

This doesn't seem necessary.

Copy link
Member Author

Choose a reason for hiding this comment

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

It's necessary to convert from IAsyncEnumerable to Enumberable

Copy link
Member

Choose a reason for hiding this comment

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

It still builds if I remove it.

Copy link
Member Author

Choose a reason for hiding this comment

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

Really!! I got 4 errors, how the IAsyncEnumerable extension methods be there without referencing a proper package?

Copy link
Member

Choose a reason for hiding this comment

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

I dunno :).

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

Out of diff range and nitpick comments (1)
src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs (1)

39-62: Consider caching the dictionary directly instead of the task to avoid potential issues with multiple concurrent requests.

@hishamco

This comment was marked as off-topic.

Copy link
Member

Choose a reason for hiding this comment

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

If the other changes in the PR prove to be suitable, then ILocalizationFileLocationProvider can be made async too.

Copy link
Member Author

Choose a reason for hiding this comment

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

Why, it just retrieve a set of locations

/// <inheritdoc />
public CultureDictionary GetDictionary(CultureInfo culture)
{
var cachedDictionary = _cache.GetOrCreate(CacheKeyPrefix + culture.Name, k => new Lazy<CultureDictionary>(() =>
Copy link
Member

Choose a reason for hiding this comment

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

The Lazyness here is important as it prevents r-entrancy. Without it multiple threads (concurrent requests?) can get into the body and run. The MemoryCache is not blocking on the factory body. With the Lazy, all concurrent requests can potentially create a Lazy instance, but only one will be added to the cache and executed.

/// <inheritdoc />
public async Task<CultureDictionary> GetDictionaryAsync(CultureInfo culture)
{
var cachedDictionary = await _cache.GetOrCreateAsync(CacheKeyPrefix + culture.Name, async (e) =>
Copy link
Member

Choose a reason for hiding this comment

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

Sicne we don't want entries to be revoked here (we don't, right? even on memory pressure), we can use a keyed Dictionary and remove the prefix on the key (because there can't be conflicts anymore). I did it recently, I am sure you will recall.

Copy link
Member Author

Choose a reason for hiding this comment

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

Can we use ConccurentDictionary?

Copy link
Member

Choose a reason for hiding this comment

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

Yes, a ConcurrentDictionary actually since a culture could be read while another one is being added to it. But still a keyed service so we don't have to use IMemoryCache. We should only use it when we need expiration rules which we don't want here.

Copy link
Member

Choose a reason for hiding this comment

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

Please also add a comment in the code to remember why we need a ConcurrentDictionary (I will forget myself)

{
private static readonly Dictionary<char, char> _escapeTranslations = new()
Copy link
Member

Choose a reason for hiding this comment

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

Perfect candidate for FrozenDictionary.
Or just remove this dictionary and use a switch the compiler is clever enough to use a dictionary of ifs based on the number of items for best performance, so we don't have to think about it too much.

Copy link
Member Author

Choose a reason for hiding this comment

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

I will create another PR for that because it might need extra testing and benchmarking

@hishamco hishamco mentioned this pull request May 2, 2024
Copy link
Contributor

github-actions bot commented May 2, 2024

This pull request has merge conflicts. Please resolve those before requesting a review.

Copy link
Contributor

github-actions bot commented Aug 7, 2024

This pull request has merge conflicts. Please resolve those before requesting a review.

@MikeAlhayek
Copy link
Member

@hishamco for instructions on how to resolve the merge conflicts due to #16572 please follow the step listed in this comment.

{
translationProvider.LoadTranslations(culture.Name, dictionary);
}
var dictionary = new CultureDictionary(culture.Name, rule ?? _defaultPluralRule);
Copy link
Member

Choose a reason for hiding this comment

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

The LoadTranslationsAsync should be move to a private AwaitedLoadtranslationAsync method with the async/await keywords such that we don't need it in the GetDictionaryAsync.

@@ -41,7 +41,7 @@ public override LocalizedHtmlString this[string name]
if (_localizer is IPluralStringLocalizer pluralLocalizer && arguments.Length == 1 && arguments[0] is PluralizationArgument)
{
// Get an unformatted string and all non plural arguments (1st one is the plural count).
var (translation, argumentsWithCount) = pluralLocalizer.GetTranslation(name, arguments);
var (translation, argumentsWithCount) = pluralLocalizer.GetTranslationAsync(name, arguments).GetAwaiter().GetResult();
Copy link
Member

@sebastienros sebastienros Sep 5, 2024

Choose a reason for hiding this comment

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

All this PR to come back to this pitfall, for every single invokation of the localizer. It was better before, even if it was not reading the file asynchronously once)

Copy link
Member Author

Choose a reason for hiding this comment

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

Maybe because we didn't do it the right way from the beginning :)

Copy link
Contributor

github-actions bot commented Nov 5, 2024

It seems that this pull request didn't really move for quite a while. Is this something you'd like to revisit any time soon or should we close? Please comment if you'd like to pick it up.

@github-actions github-actions bot added the stale label Nov 5, 2024
@hishamco hishamco removed the stale label Nov 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Async Support for Loading Translations
4 participants